JavaScript
Event delegation
Learn to manage many child elements with a single listener on a parent.
Event delegation
When you have many similar elements (for example buttons in a list), instead of adding a separate listener to each, you add a single listener on the parent. This is called event delegation. Thanks to bubbling, the parent catches the children's events.
list.addEventListener('click', (event) => {
if (event.target.matches('button')) {
console.log('button clicked');
}
});
This means fewer listeners; it saves memory and also works for elements added later.
Finding an ancestor with closest
Sometimes the clicked element sits inside the one you want (for example an icon inside a button). The event.target.closest() method finds the nearest ancestor that matches a selector. This way you catch the right element in nested structures.
list.addEventListener('click', (event) => {
const button = event.target.closest('button');
if (button) console.log(button.textContent);
});
matches only checks the target itself; closest searches upward from the target. In nested elements, closest is safer.
Exercise Add a delegation listener on the list
Define a list variable and select the #list element. Add a single click listener and check whether the clicked element is a button with event.target.matches('button').
Show example solution
const list = document.querySelector('#list');
list.addEventListener('click', (event) => {
if (event.target.matches('button')) {
console.log('button clicked');
}
});
Test yourself
-
What is the main advantage of event delegation?
list.addEventListener('click', (event) => {
if (event.target.matches('button')) {
console.log('clicked');
}
});
- Manage many elements with a single listener
- Events fire faster
- Prevent the default behavior
- Stop event bubbling
Show answer
Manage many elements with a single listener — Correct! Delegation manages many elements with one listener.
-
Check whether the target is a button
list.addEventListener('click', (event) => {
if (event.target.____('button')) {
console.log('clicked');
}
});
Show answer
list.addEventListener('click', (event) => {
if (event.target.matches('button')) {
console.log('clicked');
}
});
-
Match methods to their meanings
- event.target
- The clicked element
- closest()
- Nearest ancestor matching selector
- matches()
- Does element match selector
Next lesson: preventDefault