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.
Here's a function that will let you add "live" events like jQuery's
.on
. It can be invoked like this:Take a look at the function comment for the description of each of those parameters.
And here's a full working demo:
What you want is to use DOM MutationObserver Events to apply the addEventListener. This DOM API is available on all major browser since 2012 I think.
I use this on to lower the google translator bar created by their snippet (https://www.w3schools.com/howto/howto_google_translate.asp). Since it creates the element dynamically (an iframe), it is the same problem you have. Just change the callback function and variables for your need.
You can learn more about this here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Use the target property in the
event
object to get the clicked element. Then, manually test for type/attributes/idsYou can use event.target
Code