Skip to content

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]

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;
}