DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on • Edited on

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

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
oculus42 profile image
Samuel Rouse

Events also have a currentTarget property, which matches this in the jQuery event handler. This is frequently used in place of target to avoid having to deal with propagation, but there are times it can be useful to know the "source" element.

Collapse
 
pcmagas profile image
Dimitrios Desyllas • Edited

#tsundereservice
Tsun, don't get the wrong idea, its not that I wanted to tell me. Baka

(I am joking 10q)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay