<div id="parent">
<div id="child1">
<div id="child2">
<div id="child3">
<div id="child4">
</div>
</div>
</div>
</div>
</div>
如何获取父元素,即如果我将目标节点作为child3
,则需要将父元素获取为child2
,child1
和父元素。有没有办法从JavaScript的子元素中获取父元素。谁可以帮我这个事?
谢谢。
答案 0 :(得分:2)
您可以使用for...in
来检查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>
答案 1 :(得分:0)
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'
这将阻止它将body和html元素添加到parents数组中