3

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?

Kooooro
  • 443
  • 1
  • 6
  • 15

4 Answers4

6

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);
}
natchkebiailia
  • 611
  • 4
  • 18
2

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);
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154
0

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.

Stuart
  • 201
  • 1
  • 11
0

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);
rule
  • 281
  • 1
  • 8