简体   繁体   English

Javascript获取具有特定类的所有祖先

[英]Javascript get ALL ancestors with specific class

This is code for searching all ancestors of specific div. 这是用于搜索特定div的所有祖先的代码。 How can I modify that code in way that I find all ancestors, but only with specific class(eg 'myclass')? 我如何才能以找到所有祖先的方式修改该代码,但只能使用特定的类(例如“ myclass”)?

 let nodes = [];
 let element = document.getElementById('find');
 nodes.push(element);
 while(element.parentElement) {
     nodes.unshift(element.parentElement);
     element = element.parentElement;
 }

 <div id="n1" class="something">
    <div id="n2" class="myclass">
         <div id="n3" class="something">
             <div id="n4" class="myclass">
                 <button id="find"></button>
             </div>
         </div>
         <div id="n5" class="something">
             <div id="n6" class="myclass">

             </div>
         </div>
     </div>
 </div>

so in this example it would find divs with id's n4 and n2 因此在此示例中,它将找到ID为n4和n2的div

Simply check if the node has the appropriate class, and push it only if it does 只需检查节点是否具有适当的类,并仅在有节点的情况下才进行推送

 let nodes = []; let element = document.getElementById('find'); nodes.push(element); while (element.parentElement) { if (element.parentElement.classList.contains('myclass')) { nodes.unshift(element.parentElement); } element = element.parentElement; } console.log(nodes); 
 <div id="n1" class="something"> <div id="n2" class="myclass"> <div id="n3" class="something"> <div id="n4" class="myclass"> <button id="find"></button> </div> </div> <div id="n5" class="something"> <div id="n6" class="myclass"> </div> </div> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM