Description
Instead of attaching a listener to every child, attach ONE listener to the parent and use event.target to determine which child was clicked.
?
Reach for when
You have a ton of children that follow the same action.
Code
// Bad: 1000 listeners for 1000 items
items.forEach(item => item.addEventListener('click', handleClick));
// Good: 1 listener using delegation
container.addEventListener('click', (event) => {
const item = event.target.closest('.item'); // find the clicked item
if (!item) return; // click wasn't on an item
const id = item.dataset.id;
handleItemClick(id);
});