<div id="parent">
<div id="child1">
<div id="child2">
<div id="child3">
<div id="child4">
</div>
</div>
</div>
</div>
</div>
<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.
2 Answers
Reset to default 5
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
You can use for...in
to check the parentNode
:
var a = document.getElementById("child3");
var arr = [];
for(var n in a){
a = a.parentNode;
if(a.nodeName == 'BODY') // return if the element is the body element
break;
arr.push(a);
}
console.log(arr);
<div id="parent">
<div id="child1">
<div id="child2">
<div id="child3">
<div id="child4">
</div>
</div>
</div>
</div>
</div>