TechnicalMedium JavaScript
What is event delegation and why is it useful?
Asked for Frontend Developer, Full-Stack Developer
Why they ask this: Tests your understanding of DOM event bubbling and performance with dynamic lists.
Answer
Most DOM events bubble up from the target element to its ancestors. Event delegation puts one listener on a parent and uses event.target to work out which child was clicked.
js
document.querySelector('#todo-list').addEventListener('click', (event) => {
const button = event.target.closest('button.delete');
if (!button) return;
button.closest('li').remove();
});Benefits:
- One listener instead of hundreds, which uses less memory.
- Works for elements added later, with no need to re-attach listeners.
Use event.stopPropagation() carefully, because it breaks delegation for listeners higher up.
Can you explain this in your own words?