HTML DOM closest() Method
Example
Find the closest element which matches the CSS selector and give it a yellow border:
var element = document.getElementById("myElement");
var closest =
element.closest(".container");
if (closest) {
closest.style.border = "10px solid yellow";
}
Try it Yourself »Definition and Usage
The closest()
method searches up the DOM tree for the closest element which
matches a specified CSS selector. It starts at the element itself, then tests
the parent, grandparent, and so on until a match is found. If a match is not
found, this method returns null.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
closest() | 41.0 | 15.0 | 35.0 | 6.0 | 28.0 |
Syntax
element.closest(selectors)
Parameter Values
Parameter | Description |
---|---|
selectors |
Required. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc. For multiple selectors, separate each selector with a comma. The returned element depends on which element that is first found in the document. Tip: For a list of all CSS Selectors, look at our CSS Selectors Reference. |
Technical Details
Return Value: |
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 specified selector(s) is invalid. |
---|
Related Pages
JavaScript Reference: The element.matches() method.