← Back to all snippets
JAVASCRIPT

Optimizing Event Handling with DOM Event Delegation

Learn how to efficiently manage events for multiple dynamic elements using a single event listener on their parent element, improving performance and simplifying code in web applications.

document.getElementById('parent-list').addEventListener('click', function(event) {
  // Check if the clicked element is an <li> item
  if (event.target && event.target.nodeName === 'LI') {
    const listItem = event.target;
    console.log('Clicked item ID:', listItem.id);
    console.log('Clicked item text:', listItem.textContent);
    
    // Example: Toggle a 'selected' class
    listItem.classList.toggle('selected');
  }
});

// HTML Structure example:
// <ul id="parent-list">
//   <li id="item1">Item One</li>
//   <li id="item2">Item Two</li>
//   <li id="item3">Item Three</li>
// </ul>
How it works: Event delegation is a powerful technique where you attach a single event listener to a common parent element, rather than individual listeners to each child. When an event (like a click) occurs on a child, it 'bubbles up' to the parent. The listener on the parent then uses `event.target` to identify which specific child element triggered the event, allowing you to handle it efficiently for both existing and dynamically added children, reducing memory usage and improving performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs