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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |