A list has 1,000 items, each needs a click handler. Best approach?
Options
- Attach 1,000 separate listeners, one for each item
- Event delegation: one listener on the parent element (Correct option)
- Inline
onclickattributes written on each item - Poll the list every second to check for clicks
Answer
Event delegation: one listener on the parent, use event.target.closest(...)
Why
When you click an element, the event 'bubbles' up through all its parents.
So you can put ONE listener on the list container and check which item was clicked with event.target.closest("li").
It uses less memory and automatically works for items added later.
list.addEventListener("click", (e) => {
const item = e.target.closest("li");
if (item) select(item.dataset.id);
});Remember
Many similar elements → one listener on the parent.