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?

2

4 Answers 4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

why not "onclick"?
To know more about delegation, check this answer stackoverflow.com/a/6348597/823369
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.