<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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With