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

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