← Back to all snippets
JAVASCRIPT

Implement Event Delegation for Dynamic DOM Elements

Master event delegation in JavaScript to efficiently handle events on dynamically added elements or large lists by attaching a single listener to a parent element.

// HTML: <ul id="parentList"><li>Item 1</li><li>Item 2</li></ul>
const parentList = document.getElementById('parentList');

// Add an event listener to the parent element
parentList.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'); // Add/remove a 'selected' class
  }
});

// Dynamically add a new list item after setup
const newItem = document.createElement('li');
newItem.textContent = 'Item 3 (new)';
parentList.appendChild(newItem);

// The event listener still works for 'Item 3 (new)' because it's attached
// to the parentList, not individual list items.
How it works: Event delegation is a technique where you attach a single event listener to a common parent element, rather than individual children. When an event bubbles up from a child to the parent, you can use `event.target` to identify which specific child element triggered the event. This is highly efficient for lists with many items or for elements added dynamically after initial page load, as it avoids attaching and detaching many individual listeners.

Need help integrating this into your project?

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

Hire DigitalCodeLabs