JavaScript Interview Question: What Is Event Delegation?
Short answer: event delegation means attaching one listener to a parent element instead of one per child. It works because most DOM events bubble up from the element where they happened through its ancestors.
<ul id="todo-list">
<li data-id="1">Buy milk <button class="delete">x</button></li>
<li data-id="2">Write report <button class="delete">x</button></li>
<!-- items are added and removed dynamically -->
</ul>
document.getElementById('todo-list').addEventListener('click', (event) => {
const button = event.target.closest('button.delete');
if (!button) return; // click wasn't on a delete button
const item = button.closest('li');
removeTodo(item.dataset.id);
item.remove();
});
Why use it
- Dynamic content: works for items added later, with no re-binding.
- Performance and memory: one listener instead of thousands.
- Simpler cleanup: remove one listener.
Event phases (follow-up)
- Capture: from
windowdown to the target (listeners with{ capture: true }). - Target: on the element itself.
- Bubble: back up to
window(the default foraddEventListener).
Details to mention
event.targetis the innermost element clicked (maybe an icon inside the button);event.currentTargetis the element the listener is on. Useclosest()to find the element you care about.event.stopPropagation()stops bubbling, which can break delegation elsewhere; use it sparingly.- Some events don't bubble (
focus,blur,mouseenter); usefocusin/focusoutor capture instead. - React attaches its own delegated listeners at the root, which is why this concept shows up in framework questions too.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.