Skip to content
Advertisement

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

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

for example for element <A> it would be:

[HTML, BODY, DIV, DIV, P, SPAN, A]

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement