Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Javascript changing a specific element in a div

So I have something like this in my html:

<div id="basket">
    <div id="item">Apple</div>
</div>
<div id="basket">
    <div id="item">Orange</div>
</div>
<div id="basket">
    <div id="item">Banana</div>
</div>
// And so on

How would I be able to change the innerHTML of each 'item' div individually? For example, how would I change the div that says 'banana' to something else?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As already mentioned within the comments, an ID has to be unique so you have to change them to classes.

Then to solve your issue, you can use querySelectorAll to select all elements with the class item. Then you sue the forEach-loop and check the innerHTML of every Element. if it matches "Banana" you can rewrite the innerHTML (should use textContent though for security reasons):

document.querySelectorAll('.item').forEach(el =>  {
  if (el.textContent == 'Banana') {
    el.textContent = 'The Minions ate the Banana';
  }
})
<div class="basket">
  <div class="item">Apple</div>
</div>
<div class="basket">
  <div class="item">Orange</div>
</div>
<div class="basket">
  <div class="item">Banana</div>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!