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?
            Asked
            
        
        
            Active
            
        
            Viewed 8,521 times
        
    3
            
            
        - 
                    1This is a doc for vanilla js : http://www.w3schools.com/js/js_htmldom_eventlistener.asp – Fefux Dec 02 '16 at 10:40
- 
                    1see this post:http://stackoverflow.com/questions/6956258/adding-onclick-event-to-dynamically-added-button – Suchit kumar Dec 02 '16 at 10:43
4 Answers
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
- 
                    1
- 
                    To know more about delegation, check this answer http://stackoverflow.com/a/6348597/823369 – Kishore Kumar Dec 02 '16 at 11:57
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
