"e.target" calling wrong target?
Behavior is as expected. Per MDN, event.target
is
A reference to the object that dispatched the event. It is different from
event.currentTarget
when the event handler is called during the bubbling or capturing phase of the event.
The innermost element that was clicked on was the img
, so the img
is the target
of the event.
If you wanted a reference to the element the handler is on, use e.currentTarget
instead:
$('.star-span').click(e => {
console.log(e.currentTarget);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star-span" id="1">
<img class="star-img" width="15%" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/2000px-Five-pointed_star.svg.png" />
</span>
What you are looking for is the e.currentTarget
and not e.target
. Check the snippet. e.currentTarget
is what you assigned the listener to. e.target
is what actually dispatches the event (whatever is under the mouse)
$(() => {
$('.star-span').click(e => {
console.log(e.currentTarget);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star-span" id="1">
<img class="star-img" width="15%" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/2000px-Five-pointed_star.svg.png" />
</span>
As others have answered using e.currentTarget
can work. There is also one more way using function
instead of arrow
and you will have benefit of having this
object also. You can also use e.currentTarget
here.
$(() => {
$('.star-span').click(function(e){
console.log(this);
console.log(e.currentTarget);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star-span" id="1">
<img class="star-img" width="15%" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Five-pointed_star.svg/2000px-Five-pointed_star.svg.png" />
</span>