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.
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.
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.
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"); } }
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); })();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With