Reputation: 4327
I am reading a tutorial here
the basic plugin it create is like this:
$.fn.greenify = function() {
this.css( "color", "green" );
};
$( "a" ).greenify();
My question is what's the difference if I use:
$(this).css();
instead of using
this.css();
Upvotes: 0
Views: 53
Reputation: 781726
this
is already a jQuery object, so it's not necessary to call $()
. If you give $()
a jQuery object as the argument, it creates a new jQuery object containing the same elements. So this
and $(this)
will be equivalent, but there's unnecessary overhead in making the copy.
You need to use $(this)
when this
is a DOM element rather than a jQuery object. For instance, in event handlers, this
is the DOM element that the event was triggered on, not a jQuery wrapper for the element.
Upvotes: 1
Reputation: 1384
In that specific case, this
is already a JQuery object, as shown here :
$.fn.greenify = function() {
this.css( "color", "green" );
};
Notice that greenify
is defined as a function in JQuery.
In other cases, using $(this)
might be necessary because this
might refer to the HTML DOM object, rather than a JQuery object.
Upvotes: 1
Reputation: 262684
If you make the call on an object, as you do here
$( "a" ).greenify();
then inside the function this
will point to the object.
That is not particular to jQuery, that is just how Javascript objects work.
So in this case, this
will be $("a")
, i.e. already a jQuery object (you can wrap it in $()
again, that won't hurt, but it is redundant).
In other situations (such as when interacting with the DOM directly), this
may be something else. If it is a DOM node and you want to use it with jQuery, you have to "upgrade it", by wrapping it in $()
.
Upvotes: 1
Reputation: 707696
Inside a jQuery plug-in method, this
is already the host jQuery object. So, doing $(this)
will work, but it's redundant (creates yet a new jQuery object with the same DOM elements in it) and thus is wasted code. So, this works fine:
$.fn.greenify = function() {
this.css( "color", "green" );
};
This is true for all jQuery plug-in methods.
However, in other contexts like inside an event handler such as this:
$("myButton").click(function(e) {
// this is the DOM element
$(this).css("color", "red");
});
this
is just the DOM element so you need to do $(this)
if you want a jQuery object to work with.
Upvotes: 1