I dont understand why addEventListener work once?
let input = document.querySelector(".send");
let i = 0;
input.addEventListener('click',(e)=>{
e.preventDefault();
i+=1;
document.body.innerHTML += i;
});
<input type="submit" class="send">
This is because of this line:
document.body.innerHTML
that "removes" the former set listener. You actually alter the html in a way that this listener loses track of the input-element.
You could use createTextNode to fix this or createElement and appendChild to use a newly created HTML-Node instead:
var input = document.querySelector(".send");
var i = 0;
input.addEventListener('click',function(e){
e.preventDefault();
i+=1;
// option 1: use a new node, but in order to prevent the same innerHTML bug again use option 2 instead
//var newNode = document.createElement("span");
//newNode.innerHTML = i;
//document.body.appendChild(newNode);
// option 2 use createTextNode so that innerHTML is not used at all
document.body.appendChild(document.createTextNode(i));
});
<input type="submit" class="send">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With