简体   繁体   English

更改 HTML innerText in element with duplicates

[英]Change HTML innerText in element with duplicates

I want to specifically change the innerText of the "quantity" div from this HTML:我想专门更改此 HTML 中“数量”div 的 innerText:

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

I tried using document.querySelector('.quantity').innerText = "" .我尝试使用document.querySelector('.quantity').innerText = "" But that only changes the first occurring div with the class "quantity", which is within "Div nr. 1".但这只会改变第一个出现的 div,其“数量”为 class,位于“Div nr.1”之内。

How do I specifically target the "quantity" class within "Div nr. 2"?我如何专门针对“Div nr. 2”中的“数量”class?

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="";鉴于您提供的 html,您可以 select 第二个.item然后下降到它的.details ,如下所示: document.querySelector('.item:nth-child(2).quantity').innerText="";

https://jsfiddle.net/6L8gntmh/ 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.如果您可以访问 html,那么让 id 唯一是明智的。然后您就可以通过他们的 id 访问 select。

You can use querySelectorAll this allows you to modify HTML elements based on class and id not just one of each.您可以使用 querySelectorAll 这允许您修改 HTML 元素基于 class 和 id 而不是每个元素之一。

document.querySelectorAll('.quantity')[1].innerText = "my text" document.querySelectorAll('.quantity')[1].innerText = "我的文本"

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.所有 id 必须是唯一的并且可以以数字开头,但是 select 很痛苦,我建议您的 id 以字母开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM