Favorites

DOM Element.closest() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Element.closest()
DOM Element MethodThis method is supported by all modern browsers.
Updated 28th November 2026

The closest() method searches up the tree from an element and returns the nearest ancestor, or the element itself, that matches a CSS selector.

Description

The closest() method starts at the element and travels up through its ancestors, returning the first one that matches the selectors, including the element itself. It returns null if none matches.

It's the key to event delegation: with one listener on a container, event.target.closest('button') finds the button that was clicked even if the click landed on an icon or text inside it.

Because it includes the element itself, el.closest('.card') returns el when it already has the card class. It only looks upwards, never at siblings or descendants, and stops at the document root.

Syntax

element.closest(selectors)

Parameters

  • selectorsA string of one or more CSS selectors.

Return Value

The nearest matching ancestor (or the element itself), or null if none matches.

Example

<ul id="list">
  <li>Item 1 <button data-id="1"><b>&times;</b> Delete</button></li>
  <li>Item 2 <button data-id="2"><b>&times;</b> Delete</button></li>
</ul>
const list = document.getElementById('list');
list.addEventListener('click', e => {
  const btn = e.target.closest('button[data-id]');
  if (btn) console.log('Delete item', btn.dataset.id);
});
list.querySelector('b').click();   // click lands on the <b> inside the button

Browser Support

The following information will show you the current browser support for the Element.closest() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee