JAVASCRIPT
Efficient Event Handling with DOM Event Delegation
Efficiently handle events for multiple child elements using a single event listener on a parent. This optimizes performance, simplifies code, and supports dynamic content.
document.getElementById('parentContainer').addEventListener('click', function(event) {
if (event.target.matches('.clickable-item')) {
console.log('Clicked item ID:', event.target.id);
// Perform action specific to the clicked item
}
});
How it works: This snippet demonstrates event delegation, a technique where a single event listener is attached to a common parent instead of individual child elements. When an event, like a click, occurs on a child, it 'bubbles up' to the parent. The `event.target.matches()` method then checks if the clicked element matches a specific CSS selector, allowing for efficient event handling on dynamically added or numerous elements without attaching multiple listeners.