I want to add a click event to elements with class item
. Work fine:
const enlargables = document.querySelectorAll('.item');
enlargables.forEach(function(el) {
el.addEventListener('click', function(e) {
alert('hello');
})
});
<div class="item">test 1</div>
<div class="item">test 2</div>
But if the element is added dynamically after pageload, the event will not be added to the element.
How can I add the event to newly added elements with class item
using pure JS? Similar to how document ready works in jQuery.
2
Answers
This is happening because your .item element is dynamically created. In other words, it is attached to the DOM later after your listeners are already assigned. Even delegation should be used to achieve this
JavaScript:
jQuery:
You can use event delegation on the nearest static ancestor.