Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an event listener to an element that doesn't exist yet in vanilla javascript

Tags:

In JQuery I can do:

$(document).on("click","a.someBtn",function(e){     console.log("hi"); }); 

to add an event listener to an element that doesn't exist yet. I cannot seem to figure out how to add an event listener to an element that does not exist yet in vanilla javascript.
The following does not work obviously:

query.addEventListener( "click", someListener ); 

Edit

What I would like to do is compare the item by query selectors. I am selecting the element that does not exist yet with querySelectorAll. It is a little more dynamic than just checking the tag name.

like image 847
Johnston Avatar asked Jun 02 '15 16:06

Johnston


People also ask

Can you add an event listener to a function in JavaScript?

You can add event listeners to any DOM object not only HTML elements. i.e the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling.

Can you add an event listener to a class in JavaScript?

Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements. Use the addEventListener() method to add an event listener to each element.


2 Answers

Use the target property in the event object to get the clicked element. Then, manually test for type/attributes/ids

document.addEventListener( "click", someListener );  function someListener(event){     var element = event.target;     if(element.tagName == 'A' && element.classList.contains("someBtn")){         console.log("hi");     } } 
like image 120
AmmarCSE Avatar answered Sep 29 '22 06:09

AmmarCSE


You can use event.target

A reference to the object that dispatched the event.

Code

(function () {     "use strict";         document.getElementsByTagName('body')[0].addEventListener('click', function(e) {         if (e.target.tagName == 'A' && e.target.classList.contains("someBtn")) {           alert('Clicked');         }       }, false); })(); 

(function() {    "use strict";    var a = document.createElement('a');    a.textContent = 'Click Me';    a.href = '#';    document.body.appendChild(a);      document.getElementsByTagName('body')[0].addEventListener('click', function(e) {      if (e.target.tagName == 'A') {        alert('Clicked');      }    }, false);  })();
like image 36
Satpal Avatar answered Sep 29 '22 04:09

Satpal