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

前端 未结 6 2172
执笔经年
执笔经年 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条回答
  •  攒了一身酷
    2020-12-08 10:42

    You can try something like:

    var nodes = [];
    var element = document.getElementById('yourelement');
    nodes.push(element);
    while(element.parentNode) {
        nodes.unshift(element.parentNode);
        element = element.parentNode;
    }
    

提交回复
热议问题