What's the difference between $(this)
and this
in jQuery, and why do they sometimes give the same result and other times behave differently?
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
The value of this inside a click event is a DOM element (the one that was clicked). Using $(this) converts it to a jQuery object. DOM elements do not have a hide() methods, but jQuery adds that and many other methods you can then call.
$(this) refers to the jQuery object created from current HTMLElement object.
$(this)
wraps this
with the jQuery functionality.
For example, this code would fail:
$('.someDiv').onClick(function(){
// this refers to the DOM element so the following line would fail
this.fadeOut(100);
});
So we wrap this
in jQuery:
$('.someDiv').onClick(function(){
// wrap this in jQuery so we can use jQuery fadeOut
$(this).fadeOut(100);
});
$(this)
decorates whatever object this
points to with the jQuery functions. The typical use case is for this
to reference a DOM element (say, a <div>
). Then, writing $(this)
allows you to use all the jQuery API functions on that <div>
.
If this
already refers to a jQuery object - usually a jQuery-decorated DOM object - then calling $(this)
will have no effect because it's already decorated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With