Kooooro
Kooooro

Reputation: 453

Add "onclick" handler to a dynamically created element in pure 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?

Upvotes: 3

Views: 8827

Answers (4)

natchkebiailia
natchkebiailia

Reputation: 631

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);
}

Upvotes: 6

rule
rule

Reputation: 281

from: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

HTML Content

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

JavaScript Content

// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);

Upvotes: 0

Stuart
Stuart

Reputation: 201

This example will create a button with some text and add it to an element with the id of test.

var btn = document.createElement('button');
btn.appendChild(document.createTextNode('test'));

btn.addEventListener('click', function() {
    alert('it works');
}, false);

document.getElementById('test').appendChild(btn);

Hopefully this will help you out.

Upvotes: 0

Kishore Kumar
Kishore Kumar

Reputation: 12874

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);

Upvotes: 2

Related Questions