Javascript event Listeners are not working on updating the DOM.
**HTML CODE: **
<div class="task-list">
</div>
**JAVASCRIPT CODE: **
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.