Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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] 
like image 390
rsk82 Avatar asked Jan 04 '12 15:01

rsk82


People also ask

How do I get parent node element?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.

What is the difference between parentNode and parentElement?

parentNode gives the parent, while . parentElement gives undefined.


2 Answers

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; } 
like image 187
Wayne Avatar answered Sep 25 '22 20:09

Wayne


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; } 
like image 31
techfoobar Avatar answered Sep 25 '22 20:09

techfoobar