Reputation: 453
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
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
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
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
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