Jelena M.
Jelena M.

Reputation: 15

Javascript get ALL ancestors with specific class

This is code for searching all ancestors of specific div. How can I modify that code in way that I find all ancestors, but only with specific class(e.g. '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

Upvotes: 0

Views: 1249

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

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>

Upvotes: 1

Related Questions