tags:

views:

72

answers:

3

What is the difference between $(this) and this in jQuery ? Here are two different usage :

 $(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();
     });
   });
 });
+7  A: 

The difference is that this by itself is a reference to the dom object that the event is acting upon. $(this) is creating a jquery object from that dom object.

EDIT: So with the DOM object you aren't going to have access to all the jquery added functionality but only what the dom allows. Basically you can think of the this by itself as the same as if you did document.getElementById(id)

spinon
+7  A: 

The "this" variable refers (in such cases as the event handlers you've supplied) to a DOM element. Thus $(this) is a jQuery object containing just that one DOM element.

You should use plain "this" when the native DOM APIs suffice, and $(this) when you need the help of jQuery. Your second example is a good illustration; another might be when you just need the "id" or "name" of an element.

Pointy
+6  A: 

$(this) is a jquery object while this refers to native dom object

Giorgi