Using closest() for Nested Structures
You'll learn how to reliably find the right ancestor element when handling events on complex, nested HTML structures.
The Problem with Nested Elements
When using event delegation, clicking on a deeply nested element (like an icon inside a span inside a button) can make event.target point to the wrong element—the innermost one you actually clicked, not the element you intended to handle. This makes filtering with matches() unreliable in nested scenarios.
How closest() Solves This
The element.closest(selector) method walks up the DOM tree from the clicked element, checking itself first, then each ancestor, until it finds a match for your selector. This is perfect for delegation because you don't care exactly what was clicked—you want to find the nearest parent that matters.
Think of it like an elevator: You press a button, but you're actually standing on floor 5. closest('.my-floor') rides the elevator up, checking each floor until it finds one with class my-floor.
Delegation Pattern with closest()
document.querySelector('.task-list').addEventListener('click', function(event) {
// Find the nearest ancestor (or self) matching '.task-item'
const taskItem = event.target.closest('.task-item');
if (taskItem) {
// Now we reliably have the task container, regardless of what was clicked
console.log('Task clicked:', taskItem.dataset.id);
}
});
Even if your HTML has <div class="task-item"><span><i>Icon</i></span>Text</div> and the user clicks the <i>, closest('.task-item') will find the outer div.
Key Takeaway: Use event.target.closest(selector) in delegated handlers to reliably find the intended ancestor element, even when events fire on deeply nested children.