Reputation: 8606
I am new to jquery. I want to know the difference between this
and $(this)
. Suppose i made a function call like this
$.fn.column = function() {
var $td = this;
var $td1 = $(this);
}; //end of $.fn.column = function()
$('#FaqGridForm\\:faqGrid tr td').column();
When i use firebug, then both variables are [td]
. So what is the difference between these two ?
Upvotes: 1
Views: 1547
Reputation: 165941
In that case, there is no real difference. Since you've extended jQuery, this
is already an instance of jQuery and all $(this)
does is pass it into jQuery again, which is unnecessary.
However, in cases like this:
$("#someElem").click(function() {
//this is now a reference to a DOM element:
console.log(this instanceof jQuery); //false
console.log(this.val()); //TypeError
});
You often need to pass this
into jQuery so you can use jQuery methods on it:
$("#someElem").click(function() {
console.log($(this) instanceof jQuery); //true
console.log($(this).val()); //Prints value
});
Upvotes: 1
Reputation: 337550
this
is the native DOM element in question. You can use the full gamut of DOM methods on it.
$(this)
is the native DOM element wrapped in a jQuery object, and as such you can access all the functions jQuery provides in it's framework to amend the element as you require. You can also access the DOM element itself via the jquery object by using:
$("#myElement")[0]
Update
This obviously applies to writing jQuery in external functions. Rob W is correct in that your example uses a plugin, therefore this
would refer to a jQuery object containing an element.
Upvotes: 0
Reputation: 348962
In a jQuery plugin, this
points to the jQuery collection of all matched elements. Using $(this)
in this context is obsolete, and discouraged.
In the context of, say, an event handler, this
points to the DOM element from which the event is fired. $(this)
will wrap the DOM element in a jQuery object, so that jQuery methods are available.
Code examples:
$.fn.plugin = function() { alert(this); };
$('selector').plugin(); //Alerts [object Object] = a jQuery object.
$('body').click(function() {
alert(this); // [object HTMLBodyElement]
alert($(this));// [object Object] (a jQuery object)
});
Upvotes: 3