What's the difference between $(this) and this in jQuery, and why do they sometimes give the same result and other times behave differently?
- 8,198
- 71
- 51
- 66
- 1,564
- 1
- 21
- 30
-
1when do they "*give the same result*" ? – gion_13 Oct 19 '11 at 13:20
7 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);
});
- 242,243
- 40
- 408
- 536
$(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.
- 354,903
- 100
- 647
- 710
If in your current context if the this is not a jQuery object, you can make it a jQuery element by wrapping it around $(). When your element already is a result of jQuery expression, the this in that case is already a jQuery object. So in that case they both work similarly
- 17,402
- 12
- 56
- 86
for you to understand a little bit better, get yourself a debugger of somekind such as google chrome and do this..
$('a').click(function(){
console.log(this); //DO
console.log($(this)); //JO
});
this will show you what the difference is :)
- 56,863
- 21
- 114
- 161
this is a javascript variable created whenever you are inside a function which is attached to an object. In these cases, this refers to that object.
$(this) returns a jQuery object which you can call jQuery functions on, but will apply only to this.
For example, if you set a click handler for all anchors:
$('a').click(function() {
console.log(this.href) ;
}) ;
then the this, refers to the anchor, which the click event (function) is attached to.
- 7,289
- 2
- 26
- 23
In JavaScript this always refers to the “owner” of the function that is executing. Using $(this) will only wrap the owner so that all the jQuery operations will be extended and available to it.
Consider:
$links = $('#content a');
$links.click(function() {
link = this;
$link = $(this); //jQuery wrapped object.
alert(link.getAttribute('href'));
alert($link.attr('href')); //we can use the attr() function from jQuery
});
They usually give the same results since the owner is the same, only that when wrapped by jQuery it can operate with the jQuery functions.
- 2,174
- 1
- 21
- 32