.closest()
Element? Element.closest(String selectors)
Warning! Current browsers do not yet support
.closest(), please
use a polyfill
until they do.
Closest element of the element itself and its ancestors, in order from the element to the root.
let result = element.closest(selectors);Returns the first (starting at element) inclusive ancestor that match selectors.
Examples
HTML:
<ul class="list-one">
<li class="one">Item 1</li>
<li>
<ul class="list-two">
<li class="two">Item 2</li>
<li class="three">Item 3</li>
</ul>
</li>
</ul>Example 1
JavaScript:
let result = document.query(".two").closest("ul");Result is the <ul class="list-two">...</ul> element.
Example 2
JavaScript:
let result = document.query(".two").closest("li");Result is the <li class="two">Item 2</li> element.
Example 3
JavaScript:
let result = document.query(".two").closest(".list-one");Result is the <ul class="list-one">...</ul> element.