JAVASCRIPT
Implement Event Delegation for Efficient DOM Event Handling
Learn how to use event delegation in JavaScript to manage events on multiple elements efficiently, reducing memory footprint and improving performance for dynamic content.
const parentElement = document.getElementById('myList');
parentElement.addEventListener('click', function(event) {
// Check if the clicked target is an LI element or a child of an LI
let targetListItem = event.target.closest('li');
if (targetListItem && parentElement.contains(targetListItem)) {
console.log('Clicked item:', targetListItem.textContent);
targetListItem.classList.toggle('highlight');
}
});
// Example HTML for context:
// <ul id="myList">
// <li>Item One</li>
// <li>Item Two</li>
// <li>Item Three</li>
// </ul>
How it works: This snippet demonstrates event delegation, a powerful technique for handling events on multiple child elements efficiently. Instead of attaching a click listener to every `<li>` item, a single listener is added to their parent `<ul>`. When a click occurs, the event bubbles up to the parent. We then use `event.target.closest('li')` to identify which specific `<li>` (or its child) was clicked, making event management efficient, especially for dynamic lists, and reducing the number of event listeners in memory.