Course contentsShow
← Web Development
Lesson 765 of 2,98213. DOM EventsFree lesson

Common Delegation Pitfalls

Avoiding issues with stopPropagation(), checking for null closest() results, and managing nested delegated listeners.

Common Delegation Pitfalls

You'll learn how to avoid the most common mistakes when implementing event delegation.

Event delegation is powerful, but it's easy to trip up if you're not careful about a few key issues.

The stopPropagation() Problem

When you use stopPropagation() on an event somewhere in your DOM tree, it prevents the event from reaching your delegated listener. Imagine setting up a catch-all listener on a parent, but someone else's code stops the event before it bubbles up—your handler never fires. Solution: Be very cautious about using stopPropagation() in applications that rely on delegation, and document where you use it.

The Null closest() Result

When filtering delegated events with closest(), you might assume it always finds something. But closest() returns null if no matching ancestor exists (including the element itself). If you try to access properties on that null value, you'll get an error:

list.addEventListener('click', function(event) {
  const item = event.target.closest('.item');
  // If clicked outside any .item, item is null!
  item.classList.toggle('selected'); // ❌ Error if null
});

Solution: Always check for null before using the result:

const item = event.target.closest('.item');
if (item) {
  item.classList.toggle('selected'); // ✅ Safe
}

Nested Delegated Listeners

Attaching multiple delegated listeners to nested elements can cause handlers to fire multiple times for a single action. If both a parent and grandparent are listening for the same delegated event, both will respond as the event bubbles up. Solution: Choose one appropriate delegation point, or use stopPropagation() deliberately when you need to prevent further bubbling.

Key Takeaway: Event delegation requires defensive coding—always check for null results from closest(), be mindful of where stopPropagation() is used, and avoid overlapping delegated listeners on nested elements.