gpt4 book ai didi

javascript - 在类为 ="B"的元素中获取类为 ="A"的 DOM 元素

转载 作者:行者123 更新时间:2023-11-28 04:27:33 25 4
gpt4 key购买 nike

具有这种 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 method querySelectorAll() 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com