Definition and Usage
The closest() function finds and returns the closest ancestor element that matches the given CSS selector. The element itself is also included in the search. If no matching element exists, it returns null.
Basic Example
<section>
<div id="div-01" class="container">
<div id="div-02" class="container">
<div id="me">me</div>
</div>
</div>
</section>
const me = document.getElementById("me");
console.log(me.closest(".container")); // <div id="div-02" class="container">...</div>
console.log(me.closest("section > div")); // <div id="div-01" class="container">...</div>
/* The element itself is also included in the search. */
console.log(me.closest("div")); // <div id="me">...</div>
/* If no matching element exists, it returns null. */
console.log(me.closest("p")); // null
Code Explanation
The getElementById() function returns the Element object whose HTML id attribute value matches the specified string.
If no matching element exists, it returns null.
The concept that operates in the opposite direction of the closest() function is searching for descendant elements.
This involves traversing the DOM tree downward, and this is typically handled using the querySelector() function.
Syntax
element.closest(selectors)
Parameters
selectors |
The selector string used to identify the target element. Must be a valid CSS selector string. |
|---|
Return Value
- Returns the closest ancestor element that matches the given CSS selector. The element itself is also included in the search.
- If no matching element exists, it returns
null.
Exceptions
A SyntaxError is thrown if selectors is not a valid CSS selector.
Things to Keep in Mind
For example, assume the following HTML structure:
<div class="container">
<ul class="list">
<li class="item">
<span>Item 1</span>
</li>
<li class="item">
<span>Item 2</span>
</li>
</ul>
</div>
const spanElement = document.querySelector("span");
const closestListItem = spanElement.closest("li");
if (closestListItem !== null) {
console.log(closestListItem); // Output: <li class="item">...</li>
} else {
console.log("No matching element found.");
}
In the example above, we check whether closestListItem is not null to verify if the closest <li> element exists. If it is not null, it logs the corresponding element to the console, and if it is null, it outputs the message "No matching element found." This ensures that the return value of the closest() function is valid.
Browser Compatibility
| Method |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
closest()
|
41 | 15 | 35 | 6 |
Specifications
| Specification | |
|---|---|
closest()
|
DOM Standard #ref-for-dom-element-closest① |