What’s the difference between ‘$(this)’ and ‘this’?

What’s the difference between ‘$(this)’ and ‘this’?

I am currently working through this tutorial: Getting Started with jQuery
For the two examples below:
$(“#orderedlist”).find(“li”).each(function (i) {
$(this).append(” BAM! ” + i);
$(“#reset”).click(function () {
$(“form”).each(function () {

Notice in the first example, we use $(this) to append some text inside of each li element. In the second example we use this directly when resetting the form.
$(this) seems to be used a lot more often than this.
My guess is in the first example, $() is converting each li element into a jQuery object which understands the append() function whereas in the second example reset() can be called directly on the form.
Basically we need $() for special jQuery-only functions.
Is this correct?


Solution 1:

Yes you only need $() when you’re using jQuery. If you want jQuery’s help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it’s going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on…

Solution 2:

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

Solution 3:

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don’t use jQuery, you can just use this.

Solution 4:

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:


is easier and purer than


Solution 5:

this is the element, $(this) is the jQuery object constructed with that element

 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);

A deeper look

thisMDN is contained in an execution context

Solution 6:

Yeah, by using $(this), you enabled jQuery functionality for the object. By just using this, it only has generic Javascript functionality.