JavaScript·Intermediate·Coding·1 min read
What is event delegation?
Short interview answer
It attaches one listener to a stable ancestor and identifies matching descendants from the event path, commonly with closest. It handles dynamically inserted children and reduces listener setup, but requires attention to non-bubbling events and nested matching boundaries.
Example
document.querySelector('#todo-list').addEventListener('click', (e) => { const btn = e.target.closest('button[data-action="delete"]'); if (!btn) return; deleteTodo(btn.closest('li').dataset.id); // works for rows added later});Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.