Repaso
Español
Frontend & WebIntermediateFE-07

A list has 1,000 items, each needs a click handler. Best approach?

Options

  1. Attach 1,000 separate listeners, one for each item
  2. Event delegation: one listener on the parent element (Correct option)
  3. Inline onclick attributes written on each item
  4. 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.

Key terms

Practice this question in Repaso