Ask any question about JavaScript here... and get an instant response.
Why does `addEventListener` not trigger on dynamically added DOM elements, and how can I fix this?
Asked on Nov 03, 2025
Answer
When you add event listeners using "addEventListener" on elements that are dynamically added to the DOM, the listeners won't automatically apply to those new elements. This is because the event listeners are bound to elements present at the time of binding. You can fix this by using event delegation.
<!-- BEGIN COPY / PASTE -->
document.querySelector('#parentElement').addEventListener('click', function(event) {
if (event.target && event.target.matches('.dynamic-element')) {
console.log('Dynamic element clicked!');
}
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Event delegation involves setting the event listener on a parent element and using event propagation to handle events on child elements.
- In this example, "click" events on elements with the class "dynamic-element" are captured by the parent element with the ID "parentElement".
- "event.target" refers to the actual element that was clicked.
- "event.target.matches('.dynamic-element')" checks if the clicked element matches the selector for dynamically added elements.
- This approach is efficient and works for elements added after the event listener is set.
Recommended Links:
