How to recursively search all parent nodes with JavaScript?

Sometimes, we want to recursively search all parent nodes with JavaScript.

In this article, we’ll look at how to recursively search all parent nodes with JavaScript.

How to recursively search all parent nodes with JavaScript?

To recursively search all parent nodes with JavaScript, we can use the parentNode property.

For instance, we write:

<p>
  hello
</p>

to add a p element.

Then we write:

const findUpTag = (el, tag) => {
  let r = el
  while (r.parentNode) {
    r = r.parentNode;
    if (r.tagName === tag)
      return r;
  }
  return null;
}

const el = document.querySelector("p");
const body = findUpTag(el, "BODY");
console.log(body);

to define the findUpTag function that takes the el and tag parameters to search the parent of el with the given tag.

In the function, we traverse up the DOM tree starting from el by using the parentNode property to get the parent node of r.

Then we check the tag name of r with r.tagName.

If it matches tag then we return it.

And if nothing is found, we return null.

Then we call document.querySelector to select the p element.

And we call findUpTag to use it to find the body element.

Conclusion

To recursively search all parent nodes with JavaScript, we can use the parentNode property.