JavaScript Reference ยท DOM: Document and Elements
Element.closest()
Reference for Element.closest(): walk up from an element, itself included, to the nearest ancestor that matches a CSS selector, with event delegation examples.
The closest() method starts at an element and moves up the tree, checking the element itself first, then its parent, then its grandparent, and so on. It returns the first element that matches the CSS selector you give it, or null if none does.
It is the standard tool for event delegation. A click may land on an icon or a <span> inside a button; event.target.closest("button") finds the button no matter which inner element was hit.
const row = cell.closest("tr");
Try it
Syntax
element.closest(selectors)
| Name | Description |
|---|---|
selectors |
A string with a valid CSS selector list, such as "li", ".card" or "form, dialog". |
Return value: the nearest Element that matches (possibly element itself), or null.
Exceptions: SyntaxError (DOMException) if the selector string is not valid.
Usage notes
- The element itself counts.
el.closest("p")returnselif it is a<p>. If you need only true ancestors, start fromel.parentElement. - Nearest, not outermost. With several matching ancestors you get the closest one. There is no built-in way to ask for the farthest.
- Always check for
null. The target of an event may be outside the structure you expect. - Check that the match is yours. In delegation,
closest()can return an element outside the container that has the listener (if the container is nested in another matching element). Addcontainer.contains(match)when it matters. - Event targets are elements for mouse events. For events that can target other node types, guard with
event.target instanceof Elementbefore callingclosest(). - Selectors can be complex. Combinators such as
.menu > liare evaluated against the whole document, like inmatches(). - Shadow DOM.
closest()does not cross shadow boundaries. From inside a shadow tree, it stops at the shadow root.
Browser support
Supported in all current browsers.
Related
Element.matches()โ test a single element against a selectorNode.contains()โ check whether a node is inside anotherparentElement,childrenand siblings โ walk the tree manually- Lesson: Event delegation
- Lesson: DOM traversal