Skip to content
jshacks.dev
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read
Summarize in AI

An event fires on a deep child and you need the card or row it belongs to. closest walks up the tree for you.

closest.jsJavaScript
document.body.innerHTML = `
  <div class="card" id="card-1">
    <p><span id="label">Title</span></p>
  </div>`;

const label = document.querySelector('#label');

console.log(label.closest('.card').id);
console.log(label.closest('span').id);
console.log(label.closest('table'));
Text
card-1
label
null

closest(selector) tests the element itself first, then each parent, and returns the first match or null. That is why closest('span') returns the span itself. It saves a loop over parentElement and works with any selector, including attribute selectors. The method is specified in the DOM Standard.

In an event handler, use event.target.closest('.card') for delegation, and check for null, since a click may land outside any card. It exists only on elements, not on text nodes, so confirm event.target instanceof Element first when the handler can see other node types.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Build a lightbox for images

Open a full-size image in a lightbox using a native dialog, so you get the backdrop, Escape key and focus handling without a library.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.