Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
const row = cell.closest("tr");

Try it

Delegation with closest()
Self, ancestors and no match

Syntax

JavaScript
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") returns el if it is a <p>. If you need only true ancestors, start from el.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). Add container.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 Element before calling closest().
  • Selectors can be complex. Combinators such as .menu > li are evaluated against the whole document, like in matches().
  • 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.