.closest()
Example
list.addEventListener('click', (e) => {
if (e.target.matches('button')) remove(e.target);
});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.targetdirectly 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
nulland for staying inside the container withcontains().
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.
