如何在不使用 querySelectorAll 找到孙子元素的情况下找到子级元素?

How do I find child level element without finding grandchild element with querySelectorAll?

提问人:Peter H 提问时间:3/30/2023 最后编辑:Peter H 更新时间:5/6/2023 访问量:55

问:

起价<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!!
    }

});

javascript html jquery-selectors

评论

0赞 Barmar 3/30/2023
你总是只想要第一级,紧挨着?class="box"
0赞 Barmar 3/30/2023
在这种情况下,它是.box > .nested
0赞 freedomn-m 3/30/2023
可能:因为 .nested 是一个 li,而 .box 是一个 span,所以找不到任何东西。这将包括嵌套和嵌套 - 如果您只想要 node1,请首先添加一个 get。如果您的示例 HTML 指出了您想要查找哪些内容以及您不想查找哪些内容,那将会很有帮助。#tree_view > li > .box + ul > .nested.box>.nestednode 1nod 2:nth-child(0)
0赞 Peter H 3/30/2023
感谢你们的输入,我发现在一轮中进行搜索和查找太困难了,所以我选择做的仍然是找到所有“嵌套”的类,然后循环检查它们的父节点。我会把我做的代码放进去,这样它就可以帮助其他人。如果你们有某种一次性的方法来查找代码,那就更好了。

答:

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!!
    }

});