0

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.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

1

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:

document.addEventListener("click", function(e){
   const hasClass = event.target.classList.contains('item');
   if(hasClass) {
    //Add your logic here
   }
});

jQuery:

$('body').on('click', '.item', (event) => {
   //Add your logic here
});
Hazem Hagrass
  • 9,329
  • 10
  • 32
  • 54
1

You can use event delegation on the nearest static ancestor.

// document only used for demonstration
document.addEventListener('click', e => {
  // use .closest instead to handle clicks on the descendants of .item
  if (e.target.matches('.item')) console.log('click');
});

document.querySelector('button').addEventListener('click', function(e) {
  const newItem = document.createElement('div');
  newItem.classList.add('item');
  newItem.textContent = 'test';
  this.before(newItem);
});
<div class="item">test 1</div>
<div class="item">test 2</div>
<button>Add</button>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80