Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  136] [ 2]  / answers: 1 / hits: 30198  / 9 Years ago, tue, june 2, 2015, 12:00:00

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.


More From » jquery

 Answers
119

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);
}
}

[#66363] Monday, June 1, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elijahm

Total Points: 674
Total Questions: 124
Total Answers: 79

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;