Get the closest Parent Element by Tag using JavaScript

avatar

Borislav Hadzhiev

Wed Dec 29 20212 min read

banner

Photo by Wilson Szeto

Get the closest Parent element by Tag using JavaScript #

Use the closest() method to get the closest parent element by tag, e.g. child.parentElement.closest('div'). The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent-1"> <span id="parent-2"> <div id="child">Child 1</div> </span> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const child = document.getElementById('child'); // โœ… Gets immediate parent, regardless which Tag const immediateParent = child.parentElement; console.log(immediateParent); // ๐Ÿ‘‰๏ธ span#parent-2 // โœ… Gets a parent that is a `div` element const parent = child.parentElement.closest('div'); console.log(parent); // ๐Ÿ‘‰๏ธ div#parent-1

To get the DOM node's immediate parent element, we used the Node.parentElement property.

However, the parentElement property does not allow us to filter the results as it returns the parent element.

To get the closest parent element that by tag, we used the closest method.

The reason we accessed the parentElement property on the child before calling the closest() method is because the closest() method traverses theElement and its parents until it finds a node that matches the provided selector string.

In our case, the child is a div element and the parent we want to access to is a div, so calling the closest() method and passing it a div selector returns the child element.

By accessing the parentElement property we start traversing the DOM for element that match the selector from the parent element onwards.

If no element that matches the provided selector exists, the closest() method returns null.

The method takes a string that contains a selector. The provided selector can be as specific as necessary.

index.js
const child = document.getElementById('child'); // โœ… Gets a parent that is a `div` element const parent = child.parentElement.closest('body > div'); console.log(parent); // ๐Ÿ‘‰๏ธ div#parent-1

The example above selects a div element that has the body element as its parent.

If an invalid selector string is provided to the closest() method, a SyntaxError is thrown.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee