I have a code which is using Vanilla JS. Using a button I added dynamic content. But the problem is when I clicked a dynamically generated content, then it returns first click: 1 second click: 3 third click: 6 fourth click: 10
but it should be 1, 2, 3, 4
HTML Code Below:
<p>Add Content</p>
<div class="dynamic-content">
JS file Below:
let counter = 1;
document.querySelector("p").addEventListener("click", function(){
document.querySelector(".dynamic-content").innerHTML += `
<span>My dynamic content - ${counter}</span>
`;
counter++;
});
document.querySelector("body").addEventListener("click", function(){
let contentList = document.querySelectorAll(".dynamic-content span");
if(contentList.length){
contentList.forEach(function(el){
el.addEventListener("click", function(event){
console.log(event.target.innerText);
});
});
}
});
Note: We can't use jQuery