Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EventListener in javascript not working on updating DOM

Javascript event Listeners are not working on updating the DOM.

**HTML CODE:
**



    <div class="task-list">
        
    </div>

**JAVASCRIPT CODE: **

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function showList(num) {
    const taskBox = document.querySelector('.task-list'); 
    let listHtml = "";
            
    for(let i =1;i<=num;i++){
        listHtml +=  `
            <li class="list-item">Hello ${i}</li>
        `;
    }

    taskBox.innerHTML = listHtml; 
}

showList(5);


const listItem = document.querySelectorAll('.list-item'); 
listItem.forEach((item) => {
    item.addEventListener('click', (e) => {
        console.log(e.target.innerText);
        showList(4);
    }); 
}); 

With this code event Listener just working once. After that it is not working and not even showing error. So why this is happening. How to udpation of the DOM affecting eventlistener exactly.

I have faced this problem multiple times, I solved this by using onclick() function on each elmeent, but i never got solution of why it is not working in this way.

>Solution :

The reason is that after you invoke showList() again,you have replaced the old elements with new elements,and they do not have event binds,you need to add click event again

const listItem = document.querySelectorAll('.list-item'); 
listItem.forEach((item) => {
    item.addEventListener('click', (e) => {
        console.log(e.target.innerText);
        showList(4);// after create new element,need to add click event again
    }); 
}); 
function showList(num) {
    const taskBox = document.querySelector('.task-list'); 
    let listHtml = "";
            
    for(let i =1;i<=num;i++){
        listHtml += `<li class="list-item">Hello ${i}</li>`;
    }

    taskBox.innerHTML = listHtml;
    addClickEvent(); // add click event again
}

function addClickEvent(){
  const listItem = document.querySelectorAll('.list-item'); 
  listItem.forEach((item) => {
      item.addEventListener('click', (e) => {
          console.log(e.target.innerText);
          showList(4);
      }); 
  });
}

showList(5);
<div class="task-list">
        
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading