What is event delegation in JavaScript?
Quick answer
Event delegation means attaching one listener to a parent element and using event bubbling to handle events from its children, instead of adding a listener to each child.
When you click a child element, the event bubbles up through its ancestors. A single listener on the parent can inspect event.target (or use event.target.closest(selector)) to find which child was clicked and react accordingly.
This uses less memory for long lists and also works for elements added later, because the listener lives on the parent. It does not work for events that do not bubble, such as focus and blur (use focusin and focusout instead).
document.querySelector("#todo-list").addEventListener("click", (event) => {
const item = event.target.closest("li[data-id]");
if (!item) return;
removeTodo(item.dataset.id);
});