I'm dynamically creating and deleting elements "a" and "button" on a page. I want to add handlers "onclick" to them as I create them. All the examples I've seen so far were in jquery. How can I do that in pure javascript?
You can do like this:
for(var i=0;i<5;i++){
var a = document.createElement("a");
a.innerHTML="a"+i;
document.body.appendChild(a);
var button = document.createElement("button");
button.innerHTML="button"+i;
button.onclick = function(){
console.log("event on button");
}
document.body.appendChild(button);
}
You can use addEventListener to add a click listener on a dynamic button.
var btn = document.createElement("button");
btn.addEventListener('click', function(){
alert('button clicked!');
}, false);
document.body.appendChild(btn);
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