jquery 如何找到子级元素而不使用querySelectorAll找到孙级元素?

drkbr07n  于 2023-05-06  发布在  jQuery
关注(0)|答案(1)|浏览(168)

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

我试图定位<li class="nested">,它包含“叶子1”和“叶子2”,但排除了一个容器“叶子1-1”。有什么建议吗?
我尝试了多种方法,它总是找到所有子和孙元素与匹配的class. 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!!
    }

});
3phpmpom

3phpmpom1#

由于没有人发布任何进一步的解决方案,我将得出结论:

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

});

相关问题