JAVASCRIPT

Event Delegation for Efficient DOM Event Handling

Master event delegation to efficiently manage events on dynamic or numerous elements by attaching a single listener to a parent, improving performance and simplifying code.

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<script>
  const myList = document.getElementById('myList');

  myList.addEventListener('click', function(event) {
    // Check if the clicked element (event.target) is a list item
    if (event.target.tagName === 'LI') {
      console.log('Clicked on:', event.target.textContent);
      event.target.classList.toggle('selected');
    }
  });

  // Dynamically add a new item
  const newItem = document.createElement('li');
  newItem.textContent = 'New Item 4';
  myList.appendChild(newItem);
  // The event handler still works for the new item without reattaching listeners.
</script>
How it works: Event delegation is a powerful technique for handling events on multiple child elements by attaching a single event listener to their common parent. When an event bubbles up from a child, the parent's listener catches it. The `event.target` property is then used to identify the specific child that originated the event. This approach is highly efficient for lists with many items or dynamic content, as it reduces memory usage and automatically works for elements added after the initial DOM load without needing to re-bind listeners.

Need help integrating this into your project?

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

Hire DigitalCodeLabs