JAVASCRIPT

Implement Event Delegation for Dynamic Element Handling

Master event delegation in JavaScript to efficiently handle events on multiple child elements, especially useful for dynamically added content, using a single parent listener.

document.addEventListener('DOMContentLoaded', () => {
  const listContainer = document.getElementById('myList');

  if (listContainer) {
    listContainer.addEventListener('click', (event) => {
      // Check if the clicked element is an <li>
      if (event.target && event.target.matches('li')) {
        console.log('Clicked item:', event.target.textContent);
        // Add a visual feedback, e.g., toggle a class
        event.target.classList.toggle('highlight');
      }
    });

    // Example of dynamically adding an item after initial load
    setTimeout(() => {
      const newItem = document.createElement('li');
      newItem.textContent = 'New Dynamic Item 3';
      listContainer.appendChild(newItem);
      console.log('Dynamically added an item.');
    }, 2000);
  }
});

// Example HTML for context:
// <ul id="myList">
//   <li>Item 1</li>
//   <li>Item 2</li>
// </ul>
// <style>
// .highlight { background-color: yellow; }
// </style>
How it works: Event delegation is a powerful technique for handling events on multiple child elements efficiently. Instead of attaching a listener to each child, a single listener is attached to their common parent. When an event bubbles up to the parent, `event.target` identifies the actual element that triggered the event. The `matches()` method then verifies if `event.target` is the specific type of element we're interested in, allowing the event handler to respond appropriately, even for elements added dynamically after the initial page load.

Need help integrating this into your project?

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

Hire DigitalCodeLabs