Reputation: 85
First off I am using vanilla javascript (no frameworks).
I am trying to get a click event listener on an element that doesn't exist yet so I am doing this (where parentElement
exists already):
parentElement.addEventListener( "click", function(e){
console.log(e.target)
} )
The thing I am clicking looks like this:
<a href="#" class="modal-close">
<i class="fa fa-times"></i>
</a>
I am trying to get the e.target
to match the a
tag but it obviously matches the i
tag since that is what is being clicked. Therefore if I try and match the A
tag it won't match.
console.log(e.target.tagName == "A") //false
How can I match that A
tag instead of it's child (the i
tag).
I know that if I used jQuery I could just do:
$("parentElementThatExists").on("click","a.modal-close",function(e){...
That would work just fine. But I am not using jQuery.
Upvotes: 2
Views: 3238
Reputation: 1431
You could just use the e.currrentTarget
property if you don't mind. Valid for >= IE9.
http://jsfiddle.net/dpatz/6optLe9r/
Upvotes: 1
Reputation: 178413
This works for me
window.onload=function(){
var x = document.getElementById("x");
x.addEventListener( "click", function(e){
console.log(e.target.tagName,e.target.parentNode.tagName)
})
x.innerHTML='<a href="#" class="modal-close"><i class="fa fa-times">Click</i></a>'
}
<div id="x"></div>
Upvotes: 2