JavaScript’s Element.closest() method matches the Element and its ancestors against a CSS selector and returns the first matching element or null.
Syntax
Node.closest(parameter);
Parameters
A CSS selector string to match the element and its ancestors against.
Return value
The closest matching element if there is one, otherwise null.
Exceptions
SyntaxError DOMException
Thrown if the parameter is not a valid CSS selector string.
Examples
Here is an example of using the JavaScript closest() method.
Suppose we have the following HTML elements:
<div class="container-1">
<div class="container-2">
<p>JavaScript is such an interesting programming language.</p>
</div>
</div>
How can we select the closest ancestor of the p element whose class attribute starts with the string “container”?
Well, we can select the p element with the querySelector() method and call the closest() method with the CSS selector string div[class^="container"]:
let p = document.querySelector('p');
let container = p.closest('div[class^="container"]');
console.log(container.className);
You should now be able to see the value of the selected element’s class attribute (“container-2”) in the browser’s console.
Browser compatibility
|
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
closest() |
41 | 15 | 35 | 28 | 6 | 41 | 35 | 28 | 9 | 4.0 | 41 | |