Track 02 · Lesson 5 of 17Inside the browser

Track 02 · Inside the browser

Event delegation

Lesson 5 of 17· 6 min

Instead of a listener on every list item, put one listener on the list and check event.target. It uses less memory, and, crucially, it works for items added later. Add items in both versions and click them.

The bug, then the fix

Add a few items, then click the new ones

    0

    listeners attached

    0

    items that don’t respond

    1. Click the tasks, add a few, then click the new ones.
    // Runs once, on page load
    document.querySelectorAll("#todos li").forEach((li) => {
      li.addEventListener("click", () => li.classList.toggle("done"));
      li.querySelector(".del").addEventListener("click", (e) => {
        e.stopPropagation();
        li.remove();
      });
    });
    // Items added later never get these listeners.

    Why the first version breaks#

    The setup code runs once, when the page loads, and gives each existing item its own listeners. Items added later were never there when that code ran, so they never get any. It's one of the most common bugs in plain JavaScript, and it hides well: everything works until the list changes.

    How delegation works#

    Clicks bubble, so a click on any item, or on anything inside an item, eventually reaches the list. One listener there can work out which item was hit:

    • event.target is the exact element clicked, which might be a span or icon inside the item.
    • event.target.closest("li") walks up from there to the nearest list item.
    • Checking closest(".del") first tells you whether the click landed on the delete button.

    Check yourself

    Why put one click listener on a list instead of one on every item?