how to get all parent nodes of given element in pure javascript?

前端 未结 6 2181
执笔经年
执笔经年 2020-12-08 10:01

I mean an array of them. That is a chain from top HTML to destination element including the element itself.

for example for element it would b

6条回答
  •  旧时难觅i
    2020-12-08 10:48

    A little shorter (and safer, since target may not be found):

    var a = document.getElementById("target");
    var els = [];
    while (a) {
        els.unshift(a);
        a = a.parentNode;
    }
    

提交回复
热议问题