Home > database >  Change HTML innerText in element with duplicates
Change HTML innerText in element with duplicates

Time:01-27

I want to specifically change the innerText of the "quantity" div from this HTML:

<div  id="shop">
        <div id="1" > // Div nr. 1
          <div >
            <div >
              <div id="1" > // <-- Don't change this one!
            </div>
          </div>
        </div>
        <div id="2" > // Div nr. 2
          <div >
            <div >
              <div id="2" > // <-- Change this one!
            </div>
          </div>
        </div>
</div>

I tried using document.querySelector('.quantity').innerText = "". But that only changes the first occurring div with the class "quantity", which is within "Div nr. 1".

How do I specifically target the "quantity" class within "Div nr. 2"?

CodePudding user response:

Given the html you provided, you can select the second .item and then descend to its .details like so: document.querySelector('.item:nth-child(2) .quantity').innerText="";

https://jsfiddle.net/6L8gntmh/

It would be wise to make the id`s unique if you have access to the html. Then you would be able to select by their id.

CodePudding user response:

You can use querySelectorAll this allows you to modify HTML elements based on class and id not just one of each.

document.querySelectorAll('.quantity')[1].innerText = "my text"

CodePudding user response:

Depending on your specific situation, it might be more useful to use a different type of selector:

document.querySelector('#id2 .quantity').innerText = ""

All ids must be unique and can start with a number, but it's a pain to select, I would recommend starting your id with a letter instead.

  • Related