Event Bubbling and Delegation

Event bubbling means an event starts from the target element and moves up through its parent elements.

Event delegation means adding one listener to a parent and using it to handle events from child elements.

Why It Helps

Instead of adding one click listener to every button, you can add one listener to the parent container.

This is useful when:

  • there are many child elements
  • child elements are created dynamically
  • you want cleaner event-handling code

Example

const list = document.getElementById("todo-list")
 
list.addEventListener("click", function (event) {
  if (event.target.matches("button")) {
    event.target.parentElement.remove()
  }
})