skip to Main Content

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


  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
    });
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search