Ask any question about JavaScript here... and get an instant response.
Why doesn't `addEventListener` work on dynamically added elements, and how can I handle events for them in vanilla JS?
Asked on Oct 26, 2025
Answer
`addEventListener` does not work on dynamically added elements because the event listeners are bound to existing elements at the time the script runs. To handle events for dynamically added elements, you can use event delegation by attaching the event listener to a parent element.
<!-- BEGIN COPY / PASTE -->
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target && event.target.matches(".dynamic-element")) {
console.log("Dynamic element clicked!");
}
});
// Example of adding a new dynamic element
const newElement = document.createElement("div");
newElement.className = "dynamic-element";
newElement.textContent = "Click me!";
document.getElementById("parent").appendChild(newElement);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Event delegation works by setting a single event listener on a parent element.
- The event listener checks if the event target matches the desired selector (e.g., ".dynamic-element").
- This approach is efficient and works for elements added after the event listener is set.
- Ensure the parent element is present in the DOM when the event listener is attached.
Recommended Links:
