Get the closest Parent element by Class using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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

get parent element by class

We got the child element 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 matches the provided selector, 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 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.
Use the search field on my Home Page to filter through my more than 3,000 articles.