gmail user
gmail user

Reputation: 2783

What is the difference between "$(this)" and "this"?

I was reading the http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery. And got confused with use of this in these 2 code segments.

     $(document).ready(function() {
        $("#orderedlist").find("li").each(function(i) {
        $(this).append( " BAM! " + i );
       });
     });

    $(document).ready(function() {
      // use this to reset several forms at once
       $("#reset").click(function() {
        $("form").each(function() {
         this.reset();
        });
     });
   });

When do we need $(this) and this? And what is the difference between them? Thanks in advance.

Upvotes: 16

Views: 2820

Answers (5)

Blazemonger
Blazemonger

Reputation: 92893

this refers to the DOM element itself; $(this) wraps the element up in a jQuery object.

In the first example, you need $(this) because .append() is a jQuery method.

In the second example, reset() is a JavaScript method, so no jQuery wrapper is needed.

Upvotes: 17

Johnny Craig
Johnny Craig

Reputation: 5002

you only need $(this) if you are following it with a jquery function on the same line of code.

ex: $(this).find(...);    $(this).val();   etc

or else you only need this.

Upvotes: 1

user229044
user229044

Reputation: 239311

Generally in jQuery, this will be an instance of the DOM element in question, and $(this) builds a jQuery object around this which gives you the usual jQuery methods like each() and val().

Upvotes: 2

tskuzzy
tskuzzy

Reputation: 36456

this refers to a DOM object. So reset() is a function of a form DOM object. append() on the other hand is a jQuery method so it has to be called by a jQuery object, hence the $(this).

When you surround this with $, you get a jQuery object back representing that DOM object.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245419

this by itself is just a regular object.

$(this) takes this and adds the jQuery wrapper so you can use the jQuery methods with the object.

Upvotes: 7

Related Questions