Javascript get all parents element

getParents.js

Get all of an element’s parent elements up the DOM tree.

/*! * Get all of an element's parent elements up the DOM tree * (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com * @param elem The element * @param callback The test condition * @return The parent elements */ function getParents (elem, callback)  // Setup variables let parents = []; let parent = elem.parentNode; let index = 0; // Make sure callback is valid if (typeof callback !== 'function')  callback = null; > // Get matching parent elements while (parent && parent !== document)  // If using a selector, add matching parents to array // Otherwise, add all parents if (callback)  if (callback(parent, index, elem))  parents.push(parent); > > else  parents.push(parent); > // Jump to the next parent node index++; parent = parent.parentNode; > return parents; > 

Get Daily Developer Tips

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts by Chris Ferdinandi. Unless otherwise noted, all code is free to use under the MIT License.

Источник

How to get all parent elements with vanilla JavaScript

Last week, I showed you how to climb up the DOM and find the closest element with a matching selector.

Today, let’s look at how to get all parent elements of a specific element.

Setting up our helper function

Here’s our script from last week.

var getClosest = function (elem, selector)  // Element.matches() polyfill if (!Element.prototype.matches)  Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s)  var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) <> return i > -1; >; > // Get the closest matching element for ( ; elem && elem !== document; elem = elem.parentNode )  if ( elem.matches( selector ) ) return elem; > return null; >; 

Let’s first change it’s name to getParents() .

var getParents = function (elem, selector)  // Element.matches() polyfill if (!Element.prototype.matches)  Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s)  var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) <> return i > -1; >; > // Get the closest matching element for ( ; elem && elem !== document; elem = elem.parentNode )  if ( elem.matches( selector ) ) return elem; > return null; >; 

Climbing up the DOM

Instead of matching against a selector and returning the first match, we want to get all parent nodes. Let’s create an array that we’ll add each of our parent elements to.

var getParents = function (elem, selector)  // Element.matches() polyfill if (!Element.prototype.matches)  Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s)  var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) <> return i > -1; >; > // Set up a parent array var parents = []; // Get the closest matching element for ( ; elem && elem !== document; elem = elem.parentNode )  if ( elem.matches( selector ) ) return elem; > return null; >; 

When we climb up the DOM, we want to push each parent element to our array. When the loop is done, we’ll return the entire array.

var getParents = function (elem, selector)  // Element.matches() polyfill if (!Element.prototype.matches)  Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s)  var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) <> return i > -1; >; > // Set up a parent array var parents = []; // Push each parent element to the array for ( ; elem && elem !== document; elem = elem.parentNode )  parents.push(elem); > // Return our parent array return parents; >; 

Finishing touches

At this point, you have two options:

  1. Keep the script simple, and just get every parent element every time.
  2. Provide an option to filter parent elements by a selector (only returning parent elements that have a class of .pick-me , for example.

1. Get all parents

If you go this route, we can remove the selector argument from the function, and pull out the matches() polyfill.

Here’s the finished script.

var getParents = function (elem)  // Set up a parent array var parents = []; // Push each parent element to the array for ( ; elem && elem !== document; elem = elem.parentNode )  parents.push(elem); > // Return our parent array return parents; >; 

You would use it like this.

var elem = document.querySelector('.some-element'); var parents = getParents(elem); 

2. Filter by selector

If you want to filter by selector, we’ll leave both the selector argument and our matches() polyfill in place.

We need to make a small tweak to our for loop.

If a selector is provided:

  1. If the current parent element matches the selector, add it to the parent array.
  2. Skip to the next item in the loop with continue .

If no selector is provided, push the current parent element to the parent array.

var getParents = function (elem, selector)  // Element.matches() polyfill if (!Element.prototype.matches)  Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s)  var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) <> return i > -1; >; > // Set up a parent array var parents = []; // Push each parent element to the array for ( ; elem && elem !== document; elem = elem.parentNode )  if (selector)  if (elem.matches(selector))  parents.push(elem); > continue; > parents.push(elem); > // Return our parent array return parents; >; 

You would use it like this.

var elem = document.querySelector('.some-element'); var parents = getParents(elem, '.pick-me'); 

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.

Источник

How to Get All Parent Elements of an Element using JavaScript?

In HTML, every element has a parent element except for the root element which is the element of our document.

It means all the elements in an HTML document are always connected to each other in some manner. It can be a parent-child relationship, a sibling, or some other relationship. But, one thing is clear, they all are connected to each other.

So, if we want to get all parent elements of an element, we first need to get the direct parent of the element. If that is found, we can run a for/while loop to go one level up in the hierarchy to get all the parent elements.

To get the direct parent element of an element, you can use the parentNode property of the Node interface. The parentNode property is a read-only property that gives the direct parent node of the element in the DOM tree.

A DOM(document object model) tree is actually a hierarchical representation of an HTML or XML document.

Visual representation of DOM to get all parent nodes

Here is a visual representation of a DOM tree:

Let’s take an example and try to find out all the parent nodes of the given element.

Let’s say, we have the following HTML. We want to find out all the parent nodes of the element that has an id=»innerMostChild» :

Now, we need to run a while loop in our JS which will run until the given node has a parent node.

In each iteration of the while loop, we will push the parent node of the current node/element into the parentNodes array and move one level up in the DOM tree one by one.

The while loop will run until we reach the topmost element in the DOM tree which has no parent.

let element = document.getElementById('innerMostChild'); let parentNodes = []; // Array to store parent elements // Run while loop until the element has a parent node while(element.parentNode) < // Push the current parent node to array parentNodes.push(element.parentNode); // Go one level up in the DOM tree element = element.parentNode; >console.log(parentNodes); // Output: [span, li, ul, div, section, body, html, document]

As you can see from the above output, the parentNodes array contains all the parent nodes of the element including the three topmost nodes body, html & document.

Excluding the body, html and document Nodes from the Result

The document , html and body are the three topmost nodes for every child node in the DOM tree. Therefore, when we tried to get all the parent nodes of the element in the previous example, we also got these three nodes along with other parent nodes.

But sometimes we only need those parent nodes which are inside the body element as the document, html & body are common for every node. So, how do we do that?

Well, it’s quite simple. We just have to change the condition inside the while loop.

Now, instead of going up to the topmost node in the hierarchy, we will break the while loop as soon as we reach the body element.

See the following implementation:

let element = document.getElementById('innerMostChild'); let parentNodes = []; // Array to store parent elements // Break the loop as soon as we reach the body node while(element.parentNode!=document.body) < // Push the current parent node to array parentNodes.push(element.parentNode); // Go one level up in the DOM tree element = element.parentNode; >console.log(parentNodes); // Output: [span, li, ul, div, section]

As you can see from the above output, the body , html & document nodes are no longer part of the parentNodes array. This is because the while loop breaks as soon as it reaches the body node in the DOM tree.

Conclusion

In this article, we learned how we can get all parent nodes of an element with the help of JavaScript.

To get all the parent nodes of an element, we can use the parentNode property of the Nodes interface. The parentNode property gives you the direct parent node of an element. If you want to get all parent nodes, you can run a for/while loop and push all the parent nodes inside an array.

Источник

Читайте также:  Html основные теги шпаргалка
Оцените статью