Whilst developing in JS I had this case:
<a href="target" class="btn-toggle-form"><i class="fa fa-pencil"></i></a>
And I made an event listener for it using jquery:
$(".btn-toggle-form").on('click',function (e){
e.preventDefault();
const target = e.target;
console.log(target)
});
But I noticed in my console that the target
is the:
<i class="fa fa-pencil"></i>
Instead of the link!? But using this piece of code:
$(".btn-toggle-form").on('click',function (e){
e.preventDefault();
const target = e.target;
console.log(this)
});
Logs into a
instead.
The reason why it happens
The reason why it did happen is because the i
element has triggered the event. This event has been propagated till the btn-toggle-form
receives it. A easy to remember diagram is:
Creative analogy
If it still confuses you, treat the link as a catgirl's ear and the event target as her sempai. The click event is the sempai pinching the catgirls' ear. The this
points to the catgirl, because is the final receipient of the pinching (clicking) event e
. The e.target
is the sempai because is the one pinched the catgirl's ear.
(Hm,don't get the wrong idea. I didn't wrote this article just to mention catgirl. baka)