Difference between `this` and `e.target` upon a event listener in JS (using jquery)

Dimitrios Desyllas - May 24 - - Dev Community

Whilst developing in JS I had this case:

<a href="target" class="btn-toggle-form"><i class="fa fa-pencil"></i></a>
Enter fullscreen mode Exit fullscreen mode

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)
 });
Enter fullscreen mode Exit fullscreen mode

But I noticed in my console that the target is the:

<i class="fa fa-pencil"></i>
Enter fullscreen mode Exit fullscreen mode

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)
 });
Enter fullscreen mode Exit fullscreen mode

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:

Image description

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 wring idea. I didn't wrote this article just to mention catgirl. baka)

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player