← Back to all snippets
JAVASCRIPT

Event Delegation for Dynamic Content

Master event delegation in JavaScript to efficiently manage events on dynamic or numerous child elements by attaching a single listener to a common ancestor, improving performance.

const setupEventDelegation = (parentElementId, selector, eventType, handler) => {
  const parentElement = document.getElementById(parentElementId);
  if (!parentElement) {
    console.error(`Parent element with ID '${parentElementId}' not found.`);
    return;
  }

  parentElement.addEventListener(eventType, (event) => {
    const target = event.target.closest(selector);
    if (target && parentElement.contains(target)) {
      handler(event, target);
    }
  });
  console.log(`Event delegation set up for '${selector}' within '${parentElementId}'.`);
};

// Example Usage:
// HTML: <ul id="myContainer">
//         <li><button class="delete-btn">Delete A</button></li>
//         <li><button class="delete-btn">Delete B</button></li>
//       </ul>
// function handleDelete(event, button) {
//   alert(`Deleting: ${button.textContent}`);
//   button.parentElement.remove(); // Removes the <li> parent
// }
// setupEventDelegation('myContainer', '.delete-btn', 'click', handleDelete);
How it works: Event delegation is a powerful technique for handling events on multiple child elements, especially when those children are added or removed dynamically. Instead of attaching a listener to each child, a single listener is attached to a common parent. When an event bubbles up, the listener checks if the event originated from a child matching a specific selector (`event.target.closest()`) and then executes the handler. This reduces memory usage and simplifies event management for dynamic content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs