最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - Get All parent elements of an element - Stack Overflow

programmeradmin3浏览0评论

<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.

Share Improve this question edited Oct 29, 2018 at 12:50 Mamun 69k9 gold badges51 silver badges62 bronze badges asked Oct 29, 2018 at 10:06 rajraj 671 silver badge13 bronze badges
Add a ment  | 

2 Answers 2

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>

发布评论

评论列表(0)

  1. 暂无评论