Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add "onclick" handler to a dynamically created element in pure javascript

Tags:

javascript

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?

like image 263
Kooooro Avatar asked Dec 11 '25 05:12

Kooooro


2 Answers

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);
}
like image 172
natchkebiailia Avatar answered Dec 13 '25 17:12

natchkebiailia


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);
like image 37
Kishore Kumar Avatar answered Dec 13 '25 17:12

Kishore Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!