JavaScript: closest()
The closest() method searches from an element toward its ancestors and returns the nearest match for a CSS selector.
What you will learn
- What
element.closest(selector)returns, includingnull - How to find a button or card when a nested child was clicked
- Why the element itself is checked before its ancestors
- How to guard against a missing match
Minimal example
document.querySelector(".card-list").addEventListener("click", event => {
const button = event.target.closest("button[data-action]");
if (!button) return;
const card = button.closest(".card");
if (!card) return;
console.log(button.dataset.action, card);
});Even when the click lands on an icon inside a button, closest("button") finds the intended control. This is useful for event delegation because one listener can handle many current or future items.
Important points
- The selector must be valid CSS, such as
buttonor.card. - The method includes the element on which it is called, then walks toward its parent.
- It returns
nullwhen no matching ancestor exists, so check before using the result. - Use the matched element's
datasetor accessible state instead of relying on fragile DOM positions.