← Back to all snippets
JAVASCRIPT

Implementing Event Delegation for Dynamic Elements

Master event delegation in JavaScript to efficiently handle events on multiple or dynamically added DOM elements with a single event listener on a parent container.

const parentContainer = document.getElementById('parentContainer');

// Create some example dynamic children
for (let i = 0; i < 3; i++) {
  const btn = document.createElement('button');
  btn.textContent = `Item ${i + 1}`;
  btn.classList.add('dynamic-item');
  btn.style.margin = '5px';
  parentContainer.appendChild(btn);
}

parentContainer.addEventListener('click', function(event) {
  // Check if the clicked element (event.target) matches our desired selector
  if (event.target.classList.contains('dynamic-item')) {
    console.log('Clicked item:', event.target.textContent);
    event.target.style.backgroundColor = 'lightgreen'; // Visual feedback
    // Perform action specific to the clicked item
  }
});

console.log('Event listener set up on parent container.');
How it works: This code showcases event delegation by attaching a single click listener to a parent container (`parentContainer`). When a click occurs within the parent, the listener checks if the actual clicked element (`event.target`) has the class 'dynamic-item'. This method is highly efficient for handling events on many child elements, especially those added to the DOM dynamically, as it avoids attaching separate listeners to each child.

Need help integrating this into your project?

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

Hire DigitalCodeLabs