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)

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more