The home where you level up

Save my spot

.closest()

Term side of the Card.
Topic: Object on Page
Unit title: .closest()
Categories: Method
Explanation side of the Card

Explanation: The browser API method that returns the element itself or its nearest ancestor matching a given CSS selector, or `null` if none match. It's often used in event delegation to find the clicked item from `event.target`.

Browser compatibility:
  • The chrome browser supports this feature starting from version 41.
  • The edge browser supports this feature starting from version 15.
  • The firefox browser supports this feature starting from version 35.
  • The safari browser supports this feature starting from version 6.
Availability: 

Example

Wrongjs
list.addEventListener('click', (e) => {
  if (e.target.matches('button')) remove(e.target);
});
Rightjs
list.addEventListener('click', (e) => {
  const btn = e.target.closest('button');
  if (btn && list.contains(btn)) remove(btn);
});

closest() walks up from an inner icon or span to the button, so delegated clicks always match.

Common mistakes

  • Forgetting that closest() checks the element itself first.
  • Checking event.target directly and missing clicks on an icon inside the button.

Key points

  • Event delegation uses event.target.closest(), so clicks on child elements still match.
  • The result is checked for null and for staying inside the container with contains().

Interview questions

closest vs parentElement?

parentElement returns only the direct parent. closest() keeps walking up until an element matches the selector.

Does closest search child elements?

No. It checks only the element and its ancestors. Use querySelector() to search descendants.

What does closest return if nothing matches?

It returns null.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy