AddEventListener does not exist object with only Javascript

I am looking for the whole stackoverflow, but I did not get any good result regarding these problems. Change me if I'm wrong.

I want addEventListener for an object that exists or does not exist in the DOM.

In jQuery, we can simply execute the following code:

$('document').on('click', '.my-button', function () { alert("work!!!"); }); 

But how can I use only Javascript to get it? Below is my source code. But after the page loads, all newly added objects do not attach the click event.

 var Button = document.getElementsByClassName("my-button"); for(i=0;i<Button.length;i++){ document.getElementsByClassName("my-button")[i].addEventListener("click",function(){ alert("Work!!!!"); }); } 

Submit any suggestion.

+1
source share
2 answers

jQuery does not add an event listener to each div, it attaches it to the parent.

What you can do is attach the event to the parent element, and in the event handler to see its purpose is one of the buttons, and then run your function

HTML

 <div id="parent"> <div class="my-button">one</div> <div class="my-button">two</div> <div class="my-button">three</div> </div> 

Js

 document.getElementById("parent").addEventListener("click", function(event) { if ( event.target.className === 'my-button') { //Do your magic } }); 

Thus, each button you add launches your function. I don't know if the target object has a className attribute, but I suppose it's pretty simple to get an element based on the event.target object. Remember that older IE will not have the addEventListener function. Check here EventTarget.addEventListener - Web APIs | MDN

+3
source

Well, at first you do not need a second document.getElementsByClssName, and secondly, IE has a special function.

 var buttons = document.getElementsByClassName("my-button"); for(i=0;i<buttons.length;i++){ // For modern browsers if( buttons[i].addEventListener ) { buttons[i].addEventListener("click",function(){ alert("Work!!!!"); }, false ); } // For outdated IE else if( buttons[i].attachEvent ) { buttons[i].attachEvent("onclick",function(){ alert("Work!!!!"); }); } } 

EDIT:

You can also use an array of buttons as something that you create on the fly, that is:

 var button1 = document.createElement( 'button' ); var button2 = document.createElement( 'button' ); var buttons = [ button1, button2 ] // Rest of code above 
+1
source

All Articles