Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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.
<!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.
const child = document.getElementById('child'); const parentWithClass = child.closest('.parent'); console.log(parentWithClass); // 👉️ div.parent
We got the child element by its id
and called the
closest()
method on it.
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.
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.
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.
const child = document.getElementById('child'); const parentWithClass = child.closest(':not(span).parent'); console.log(parentWithClass); // 👉️ div.parent
closest()
method, a SyntaxError
is thrown.