What is event delegation in JavaScript?

Instead of adding a listener to every child, you add one listener to the parent. Thanks to bubbling, the event of a child reaches the parent, and you find the real element with event.target.

const list = document.getElementById("list");

list.addEventListener("click", (event) => {
  if (event.target.tagName === "LI") {
    console.log("Clicked: " + event.target.textContent);
  }
});

This saves memory and also works for items that are added later. See DOM EventListener.


Learn more about the similar topics:
Tutorials
JavaScript Events
JavaScript HTML DOM
JavaScript DOM Manipulation
JavaScript HTML DOM EventListener
JavaScript Forms and Validation
Exercises & Assignments
Write a JavaScript program to change the text of a paragraph on button click
Write a JavaScript program to switch dark mode on and off
Interview Questions & Answers
What is the DOM in JavaScript?
How do you select elements in the DOM?
What are events and event listeners in JavaScript?
What is event bubbling and capturing in JavaScript?
What is event delegation in JavaScript?