HTML DOM Element closest() method
- Previous Page cloneNode()
- Next Page compareDocumentPosition()
- Go Up One Level HTML DOM Elements Object
Definition and usage
closest()
The method searches for elements in the DOM tree that match the specified CSS selector.
closest()
The method starts from the element itself and then goes up the ancestor (parent, grandparent element, ...) until a match is found.
If no match is found closest()
The method returns null
.
See also:
Instance
Example 1
Find the closest element that matches the CSS selector ".container":
const element = document.getElementById("myElement"); const closest = element.closest(".container");
Example 2
Find the closest element that matches ".container" or ".wrapper":
const element = document.getElementById(".container, .wrapper"); const closest = element.closest(".container");
Syntax
element.closest(selectors)
Parameter
Parameter | Description |
---|---|
selectors |
Required. One or more (comma-separated) CSS selectors to match. Please refer to our complete CSS Selector Reference Manual. |
Return value
Type | Description |
---|---|
Object |
The closest ancestor element or the element itself that matches the specified CSS selector. Returns null if no match is found. A SYNTAX_ERR exception is thrown if the selector is invalid. |
browser support
fully supports closest()
Browser version of the method:
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 41 |
Edge 15 |
Firefox 35 |
Safari 9 |
Opera 28 |
March 2015 | April 2017 | January 2015 | October 2015 | March 2015 |
- Previous Page cloneNode()
- Next Page compareDocumentPosition()
- Go Up One Level HTML DOM Elements Object