How to Loop Through Parent Nodes in JavaScript

When dealing with a deeply nested element in the DOM sometimes we need to invoke logic on its parent elements. But not just the immediate parent ascendant, but parentNodes that are much higher up the DOM hierarchy.

So, how can you loop through parent nodes in JavaScript?

The easiest way to traverse up the DOM and retrieve a parent node is to use Element.closest. This is a nice little utility that traverses parent elements (all the way up to the document root). It will stop when it finds a node that matches the provided selectorString.

So if we have the following HTML markup:

<section>
 <div id="grand-parent">
 I am the grandparent
 </div>
  <div id="parent">
    I am the parent
    <div id="child">
      I am the child
    </div>
  </div>
</section

Let’s use .closest()in order to traverse up the DOM tree from id="child":

const childElement = document.getElementById("child");

const parentElement = childElement.closest("#parent");
// returns the element with the id of parent

const grandParentElement = childElement.closest("#grand-parent");
// returns the element with the id of parent

var divElement = childElement.closest("section > div");
// returns the closest ancestor which is a div and has a parent article

Now, the above technique isn’t a loop. So if you are looking to explicitly loop through the ascending nodes you can do the following :

const findAscendingTag = (el, tag) => {
  while (el.parentNode) {
    el = el.parentNode;
    return el.tagName === tag ? el : null;
}

var el = document.getElementById("child");
var a = findAscendingTag(el, "DIV");

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.