This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.
The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
closest(selectors)
selectorsA string of valid CSS selectors to match the Element and its ancestors against.
The closest ancestor Element or itself, which matches the selectors. If there are no such element, null.
SyntaxError DOMException
Thrown if the selectors is not a valid CSS selector.
<article>
<div id="div-01">
Here is div-01
<div id="div-02">
Here is div-02
<div id="div-03">Here is div-03</div>
</div>
</div>
</article>
const el = document.getElementById("div-03");
// the closest ancestor with the id of "div-02"
console.log(el.closest("#div-02")); // <div id="div-02">
// the closest ancestor which is a div in a div
console.log(el.closest("div div")); // <div id="div-03">
// the closest ancestor which is a div and has a parent article
console.log(el.closest("article > div")); // <div id="div-01">
// the closest ancestor which is not a div
console.log(el.closest(":not(div)")); // <article>
| Specification |
|---|
| DOM> # ref-for-dom-element-closest①> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
closest |
41 | 15 | 35 | 28 | 6 | 41 | 35 | 28 | 9 | 4.0 | 41 | 9 |
document.createElement(tagName).closest(tagName) will return null if the element is not first connected (directly or indirectly) to the context object, for example the Document object in the case of the normal DOM.Element methods that take selectors: Element.querySelector(), Element.querySelectorAll(), and Element.matches().
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest