Get the closest Parent element by Class using JavaScript

avatar

Borislav Hadzhiev

Wed Dec 29 20211 min read

banner

Photo by Jeremy Bishop

Get the closest Parent element by Class using JavaScript #

Use the closest() method to get the closest parent element by class, e.g. child.closest('.parent'). 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 class="parent"> <div id="child">Child 1</div> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const child = document.getElementById('child'); const parentWithClass = child.closest('.parent'); console.log(parentWithClass); // ๐Ÿ‘‰๏ธ div.parent

We got the child by its id and called the closest method on it.

The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

If the element itself matches the selector, the element is returned.

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'); const parentWithClass = child.closest('div.parent'); console.log(parentWithClass); // ๐Ÿ‘‰๏ธ div.parent

The example above matches only div elements that have the parent class.

The following example selects a div element that has a class of parent and has the body element as the parent.

index.js
const child = document.getElementById('child'); const parentWithClass = child.closest('body > div.parent'); console.log(parentWithClass); // ๐Ÿ‘‰๏ธ div.parent

The following example returns the closest parent, which has the parent class and is not a span element.

index.js
const child = document.getElementById('child'); const parentWithClass = child.closest(':not(span).parent'); console.log(parentWithClass); // ๐Ÿ‘‰๏ธ div.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