SmartCodingTips

Event Delegation in JavaScript

Event Delegation is a technique where a single event listener is added to a parent element to manage events triggered by its child elements. This approach improves performance and simplifies dynamic UI management.

📌 Why Use Delegation?

  • Reduces memory usage by attaching fewer listeners
  • Works even if child elements are added dynamically
  • Cleaner and scalable code for large UIs

🧠 How It Works

Events "bubble" up from the target element to its ancestors. You can use event.target to detect which child was clicked.

document.getElementById("list").addEventListener("click", function(e) {
    if (e.target.tagName === "LI") {
        alert("You clicked: " + e.target.textContent);
    }
});

✅ Example With HTML

<ul id="list">
    <li>Apple</li>
    <li>Banana</li>
    <li>Cherry</li>
</ul>

🚨 Filtering by Class or Attribute

container.addEventListener("click", function(e) {
    if (e.target.classList.contains("delete-btn")) {
        e.target.parentElement.remove(); // Remove the item
    }
});

⚠️ Be Careful With:

  • Accidental matches (use specific selectors)
  • Nested events (use e.stopPropagation() if needed)
  • DOM structure changes (ensure elements exist)
Pro Tip: Use delegation with lists, tables, and components where elements may be added or removed dynamically.