Explain Codes LogoExplain Codes Logo

What's the difference between '$(this)' and 'this'?

javascript
callback-functions
event-handling
jquery-objects
Nikita BarsukovbyNikita Barsukov·Sep 10, 2024
TLDR
// 'this' is just the HTML object who clicks the event. Not much of a talker... $("button").click(function() { console.log(this); // You're looking at a solid HTMLButtonElement }); // '$(this)' wraps up 'this' in jQuery methods. The life of the party! $("button").click(function() { console.log($(this).text()); // Chatty fellow, spits out the button's text! });

this is like a caveman's Stone Age tool for accessing the HTML element directly in a callback. $(this), on the other hand, is like our modern-day Swiss Army knife—it turns this into a versatile jQuery object that can work wonders on DOM manipulation.

Peeling Back the Layers: $(this) and this Explained

The Art of Using $(this)

In the jQuery universe, $(this) is your magic wand. It turns the base this keyword into a jQuery object—giving you instant access to a treasure trove of handy jQuery methods.

Check this out:

$('.myClass').each(function() { // It's like height-on-demand! jQuery style... console.log($(this).height()); });

The jQuery wrapper here, i.e., $(this), keeps everything neat and tidy while you run a gambit through elements, perform animations, handle events, and wreak havoc on DOM manipulation. The array-like structure of jQuery objects also provides a simple route for iteration, something that this struggles to offer without the help of jQuery.

The Simplicity of this

Sometimes less is more. When you aren't looking for abstract art but a simple reference sketch, this gives you that direct reference:

$('.myClass').each(function() { // Going incognito, for that stealthy CSS change... this.style.opacity = '0.5'; });

Here, we use this when working with basic JavaScript functions or properties and bypass jQuery's enhancement layer. All about keeping it clean and efficient.

jQuery Object vs. DOM Element

this is connected to the DOM element that initiated the event. When you trigger a jQuery function, internally, it uses apply or call to bind this inside your callback functions.

Here's a cheat sheet for you:

Property$(this)this
TypejQuery objectDOM element
MethodsjQuery methodsNative JS methods
DOM properties accessBy calling $(this).prop()Directly, e.g., this.id
PerformanceA smidge slower (due to the abstraction layer)Faster (no extra layer to pass through)

Simplified Element Selection

Recognizing when to use $(this) and when to favor this is key. In scenarios where there's only one result, like fetching by ID, it's often easier to use this or document.getElementById():

$("#myDiv").click(function() { // Both will fetch you the same DOM element, choose your fighter! console.log($("#myDiv")[0]); console.log(this); });

Practical Use Cases and Common Hurdles

The Arrow Function Quandary

$(".button").click(() => { console.log($(this)); // Expect an empty stare. `this` is a social recluse in the context of arrow functions! });

Within arrow function callbacks, this doesn't refer to the element but inherits the surrounding context. For dynamic scoping of this by jQuery, stick to the traditional function.

Juggling Event Data

$("input").on('keypress', function(event) { if (event.which === 13) { // 'this' channeling its inner Detective Conan, going after evidence (event properties)! $(this).css("background-color", "green"); // '$(this)' pulling a Bob Ross and painting the town green! } });

Efficiency Checks

$('img').on('load', function() { var imageHeight = this.naturalHeight; // Ditching the jQuery highway to ride the native lane! console.log("Image height:", imageHeight); });

Here, the naturalHeight property is directly accessible sans involving jQuery. This lean approach results in better performance.