Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What's the difference between $(this) and this in jQuery, and why do they sometimes give the same result and other times behave differently?

like image 668
Amirouche Douda Avatar asked Sep 10 '10 14:09

Amirouche Douda


People also ask

What does $( this mean in jQuery?

$(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.

When we should use $( this in jQuery?

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.

What is the meaning of $( this?

$(this) refers to the jQuery object created from current HTMLElement object.


2 Answers

$(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);
});
like image 150
Justin Niessner Avatar answered Oct 11 '22 12:10

Justin Niessner


$(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.

like image 38
Matt Ball Avatar answered Oct 11 '22 12:10

Matt Ball