Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Get All parent elements of an element

Tags:

javascript

<div id="parent">
    <div id="child1">
        <div id="child2">
          <div id="child3">
            <div id="child4">
            </div>
          </div>
        </div>
    </div>      
</div>

How to get the parent elements i.e if I take target node as child3 then need to get the parent elements as child2, child1 and parent. Is there any approach to get the parent elements from child in JavaScript. can any one help me on this? Thank you.

like image 891
raj Avatar asked Aug 26 '26 08:08

raj


1 Answers

var elem = document.getElementById("child3");

function getParents(elem) {
  var parents = [];
  while(elem.parentNode && elem.parentNode.nodeName.toLowerCase() != 'body') {
    elem = elem.parentNode;
    parents.push(elem);
  }
  return parents;
}

console.log(getParents(elem));
<div id="parent">
    <div id="child1">
        <div id="child2">
          <div id="child3">
            <div id="child4">
            </div>
          </div>
        </div>
    </div>
    
</div>
elem.parentNode.nodeName.toLowerCase() != 'body'

this will prevent it from adding body and html elements into the parents array

like image 98
fanjabi Avatar answered Aug 28 '26 21:08

fanjabi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!