具有这种 HTML 结构:
<div class="fruit">
<div class="tomato">get this one</div>
</div>
<div class="vegetable">
<div class="tomato">not this one</div>
</div>
如何使用 Javascript 获取 .fruit
元素内的 .tomato
元素,而不是 .vegetable
内的元素?
例子:
a = document.getElementsByClassName("fruit");
b = a.FunctionThatGetsTheClass("tomato");
最佳答案
另一种方法是使用选择器和函数 Document.querySelectorAll
The
Element
methodquerySelectorAll()
returns a static (not live)NodeList
representing a list of the document's elements that match the specified group of selectors.
let tomatos = document.querySelectorAll('.fruit .tomato');
let tomatos = document.querySelectorAll('.fruit .tomato');
// The function map is only to demonstrate the selected elements.
console.log(Array.from(tomatos).map(d => d.textContent));
<div class="fruit">
<div class='tomato'>tomatos#1</div>
<div class='tomato'>tomatos#2</div>
</div>
<div class="vegetable">
<div class='tomato'>tomatos#3</div>
<div class='tomato'>tomatos#4</div>
</div>
关于javascript - 在类为 ="B"的元素中获取类为 ="A"的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018287/