HTML Element .closest() / matches() Since: Selectors API(2008)
Methods for searching and testing HTML elements using CSS selectors. element.closest() searches up the ancestor tree for an element matching the selector, while element.matches() tests whether the element itself matches the selector.
Syntax
// Returns the nearest ancestor (including the element itself) that matches the selector.
var result = element.closest("selector");
// Tests whether the element itself matches the selector.
var result = element.matches("selector");
Methods
| Method | Description |
|---|---|
| closest("selector") | Traverses the DOM tree toward the root, starting from the element itself, and returns the nearest ancestor that matches the selector. Returns null if no matching element is found. |
| matches("selector") | Tests whether the element itself matches the selector and returns true or false. |
Sample Code
<div class="container"> <div class="panel"> <p id="text" class="message active">Hello</p> </div> </div>
var text = document.querySelector("#text");
// closest() searches up the ancestor tree. The element itself is also checked.
console.log(text.closest(".panel")); // Returns div.panel
console.log(text.closest(".container")); // Returns div.container
console.log(text.closest(".message")); // Returns the element itself
console.log(text.closest(".nothing")); // No match, so returns null
// matches() tests whether the element itself matches the selector.
console.log(text.matches(".message")); // Outputs true
console.log(text.matches(".active")); // Outputs true
console.log(text.matches(".panel")); // Outputs false
console.log(text.matches("p.message")); // Outputs true
Overview
element.closest() starts from the element itself and traverses the DOM tree toward the root, returning the nearest ancestor that matches the selector. The element itself is included in the search, so if the element matches the selector, it is returned directly. If no matching element is found, null is returned.
A common use case is event delegation. You register an event on a parent element using element.addEventListener(), then use element.closest() on the clicked element to find the target element. This approach also works for dynamically added elements, making it very convenient.
element.matches() tests whether an element matches a selector and is useful for conditional branching and filtering. While document.querySelector() searches down the descendant tree, element.closest() searches up the ancestor tree — they are exact opposites in direction.
Browser Compatibility
40 or earlier ×
34 or earlier ×
5 or earlier ×
Android Browser
46+ ○
40 or earlier ×
Chrome Android
46+ ○
40 or earlier ×
Firefox Android
79+ ○
34 or earlier ×If you find any errors or copyright issues, please contact us.