HTML DOM Element closest() Method
Examples
Find the closest element that matches the CSS selector ".container":
const element = document.getElementById("myElement");
const closest = element.closest(".container");
Try it Yourself »
Find the closest element that matches ".container" or ".wrapper":
const element = document.getElementById(".container, .wrapper");
const closest = element.closest(".container");
Try it Yourself »
Definition and Usage
The closest()
method searches up the DOM tree for elements which
matches a specified CSS selector.
The closest()
method starts at the element itself, then the anchestors (parent, grandparent, ...)
until a match is found.
The closest()
method returns null()
if no match is found.
Syntax
element.closest(selectors)
Parameters
Parameter | Description |
selectors |
Required. One or more (comma separeted) CSS selectors to match. See our Complete CSS Selectors Reference. |
Return Value
Type | Description |
Object |
The closest ancestor element, or the element itself, that matches the specified CSS selector(s). If no matches are found, null is returned.Throws a SYNTAX_ERR exception if the selector(s) is invalid. |
Browser Support
The first browser versions that fully support the closest()
method:
Chrome 41 |
Edge 15 |
Firefox 35 |
Safari 9 |
Opera 28 |
Mar 2015 | Apr 2017 | Jan 2015 | Oct 2015 | Mar 2015 |