Multiple elements and event delegation

INPUT · Slides

One listener for every row

01 / 03

100 rows, 100 listeners?

In chapter 1 you wrote addEventListener every time you made an li. Five rows, five listeners. What about a hundred?

There is a simpler way. Put one listener on the parent (#list) and figure out which row was pressed. This is called event delegation.

02 / 03

event.target is what was actually pressed

When a button is pressed, the event bubbles up through every parent. A listener on #list will hear it.

At that point, event.target tells you the element that was actually pressed. Check whether it is a Done button, and you know whether to remove the row or do nothing.

list.addEventListener("click", (event) => {  console.log(event.target) // the thing that was clicked})

03 / 03

closest finds the nearest match going up

event.target might be the text inside the button rather than the button itself.

event.target.closest(".done") looks at the target and then walks upward until it finds something that matches .done. If nothing matches, it returns null, and you guard against that.

list.addEventListener("click", (event) => {  const btn = event.target.closest(".done")  if (!btn) return  btn.closest("li").remove()})