{{APIRef("DOM")}}{{SeeCompatTable}}
The Element.closest()
method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null
.
Syntax
var elt = element.closest(selectors);
Parameters
- selectors is a {{domxref("DOMString")}} containing a selector list like
"p:hover, .toto + q"
- element is the {{domxref("Element")}} at the top of the tree of elements to be dealt with.
Result value
- elt is the {{domxref("Element")}} which is the closest ancestor of the selected elements. It may be null.
Exceptions
- {{exception("SyntaxError")}} is thrown if the selectors is not a valid selector list string.
Example
<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>
var el = document.getElementById('div-03'); var r1 = el.closest("#div-02"); // returns the element with the id=div-02 var r2 = el.closest("div div"); // returns the closest ancestor which is a div in div, here is div-03 itself var r3 = el.closest("article > div"); // returns the closest ancestor which is a div and has a parent article, here is div-01 var r4 = el.closest(":not(div)"); // returns the closest ancestor which is not a div, here is the outmost article
Specifications
Specification | Status | Comment |
---|---|---|
{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}} | {{Spec2('DOM WHATWG')}} | Initial definition. |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 41 | {{CompatNo}} | {{CompatGeckoDesktop("35.0")}} | {{CompatNo}} | 28 | 9 |
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | {{CompatUnknown}} | {{CompatGeckoMobile("35.0")}} | {{CompatNo}} | {{CompatUnknown}} | 9.0 |
See also
- The {{domxref("Element")}} interface.