Middle
What is event delegation?
sobes.tech AI
Answer from AI
Event delegation is a technique for handling events in JavaScript, where the event handler is attached not to each individual element, but to their common parent. When an event occurs on a child element, it bubbles up the DOM tree, and the parent handler intercepts this event, determining exactly on which element it occurred.
This allows:
- reducing the number of handlers and, consequently, the load on memory and performance;
- dynamically handling events on elements that may appear after the handler is set.
Example:
const list = document.querySelector('#list');
list.addEventListener('click', event => {
if (event.target && event.target.matches('li.item')) {
console.log('Click on list item:', event.target.textContent);
}
});
Here, the handler is set on the parent element #list, and inside it checks whether the click was specifically on an element with the class item.