← Back to all snippets
JAVASCRIPT

Efficient Event Delegation for Dynamic Elements

Improve performance and simplify event handling by using event delegation, attaching a single listener to a parent element to manage events from multiple dynamic child elements.

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

  if (!listContainer) {
    console.error('List container not found.');
    return;
  }

  // Attach a single event listener to the parent container
  listContainer.addEventListener('click', (event) => {
    // Check if the clicked element (event.target) matches our desired child selector
    if (event.target.matches('.list-item button.delete-btn')) {
      const listItem = event.target.closest('.list-item');
      if (listItem) {
        alert(`Deleting item: ${listItem.dataset.itemId}`);
        listItem.remove(); // Remove the list item from the DOM
      }
    } else if (event.target.matches('.list-item span.item-text')) {
      alert(`Clicked on item text: ${event.target.textContent}`);
      event.target.style.color = 'blue';
    }
  });

  // Function to add new items dynamically
  function addNewListItem(id, text) {
    const newItem = document.createElement('li');
    newItem.className = 'list-item';
    newItem.dataset.itemId = id;
    newItem.innerHTML = `
      <span class="item-text">${text}</span>
      <button class="delete-btn">Delete</button>
    `;
    listContainer.appendChild(newItem);
  }

  // Example: Add some initial items
  addNewListItem('item-1', 'First Item');
  addNewListItem('item-2', 'Second Item');

  // Example: Add an item later, event delegation still works
  setTimeout(() => {
    addNewListItem('item-3', 'Third Item (added later)');
  }, 2000);
});

/*
HTML structure for this example:
<ul id="myList">
  <!-- Dynamic list items will be added here -->
</ul>
*/
How it works: Event delegation is a powerful pattern where a single event listener is placed on a common parent element, rather than on individual child elements. When an event bubbles up to the parent, `event.target` identifies the actual element that triggered the event. `event.target.matches()` then checks if this element (or one of its ancestors via `closest()`) fits a specific CSS selector, making it ideal for handling events on dynamically added content without re-attaching listeners.

Need help integrating this into your project?

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

Hire DigitalCodeLabs