Element: closest() method
{{APIRef("DOM")}}
The closest() method of the {{domxref("Element")}}Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
Syntax
closest(selectors)
Parameters
selectors- : A string of valid CSS selectors to match the
{{domxref("Element")}}Element and its ancestors against.
- : A string of valid CSS selectors to match the
Return value
The closest ancestor {{domxref("Element")}}Element or itself, which matches the selectors. If there is no such element, null is returned.
Exceptions
SyntaxError{{domxref("DOMException")}}DOMException- : Thrown if the
selectorsis not a valid CSS selector.
- : Thrown if the
Examples
HTML
<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>
JavaScript
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>
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
Compatibility notes
- In Edge 15-18
document.createElement(tagName).closest(tagName)will returnnullif the element is not first connected (directly or indirectly) to the context object, for example the{{domxref("Document")}}Document object in the case of the normal DOM.
See also
- CSS selectors module
- Other
{{domxref("Element")}}Element methods that take selectors:{{domxref("Element.querySelector()")}},{{domxref("Element.querySelectorAll()")}}, and{{domxref("Element.matches()")}}.