5

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();
     });
   });
 });
penguru
  • 4,342
  • 11
  • 46
  • 56

3 Answers3

10

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
  • 405,095
  • 59
  • 585
  • 614
9

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
  • 10,760
  • 5
  • 41
  • 59
  • "`this` _by itself is a reference to the dom object that the event is acting upon_", so far the most beautiful definition for getting to know `this`, Thumbs up buddy : ) ! – Irf Nov 21 '17 at 06:33
8

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

Giorgi
  • 30,270
  • 13
  • 89
  • 125