提问人:Peter H 提问时间:3/30/2023 最后编辑:Peter H 更新时间:5/6/2023 访问量:55
如何在不使用 querySelectorAll 找到孙子元素的情况下找到子级元素?
How do I find child level element without finding grandchild element with querySelectorAll?
问:
起价<ul id="tree_view">
<ul id="tree_view">
<li>
<span class="box">Node 1</span>
<!-- recursive template -->
<ul>
<li class="nested">
<span class="box">Leaf 1</span>
<!-- recursive template -->
<ul>
<li class="nested">
<span class="non-box">Leaf 1-1</span>
<!-- recursive template -->
</li>
</ul>
</li>
<li class="nested">
<span class="non-box">Leaf 2</span>
<!-- recursive template -->
</li>
</ul>
</li>
<li>
<span class="box">Node 2</span>
<!-- recursive template -->
<ul>
<li class="nested">
<span class="non-box">Leaf 3</span>
<!-- recursive template -->
</li>
<li class="nested">
<span class="non-box">Leaf 4</span>
<!-- recursive template -->
</li>
</ul>
</li>
</ul>
我正在尝试找到容器“叶 1”和“叶 2”,但排除了一个容器“叶 1-1”。有什么建议吗?<li class="nested">
我尝试了多种方法,它总是找到所有具有匹配类 .nested 的子元素和孙子元素。我试过了:。* > * > * > .nested
我找到了解决方案,使用“节点 1”作为示例:
var boxValue = "Node 1";
const elements = this.parentElement.querySelectorAll("* > * > .nested");
elements.forEach(element => {
const parentBox = element.parentElement.parentElement.querySelector(".box");
if (parentBox.textContent == boxValue) {
//found!!
}
});
答:
1赞
Peter H
4/30/2023
#1
由于没有人发布任何进一步的解决方案,我将得出结论:
var boxValue = "Node 1";
const elements = this.parentElement.querySelectorAll("* > * > .nested");
elements.forEach(element => {
const parentBox = element.parentElement.parentElement.querySelector(".box");
if (parentBox.textContent == boxValue) {
//found!!
}
});
评论
class="box"
.box > .nested
#tree_view > li > .box + ul > .nested
.box>.nested
node 1
nod 2
:nth-child(0)