71

What is the fundamental difference between using $(this) vs this

$('.viewComments').click(function(ev){
    //returns the desired value
    alert(this.getAttribute('id'));

    //Gives an error sayin function is not defined 
    alert($(this).getAttribute('id'));

    //returns the desired value
    alert($(this).attr('id'));
});

What I thought was "$(this)" will contain all functions that "this" has and more..But that doesn't seem to be the case.

So what exactly is $(this)? and

Hw do I know what functions are available when I'm using it? (I know I can get them through firebug. but I would like to know if there any some other way- some doc may be)

Bimal Das
  • 1,882
  • 5
  • 28
  • 53
Sheldon Fernandes
  • 1,299
  • 1
  • 11
  • 18
  • possible duplicate of [Why do I have to use $(this)](http://stackoverflow.com/questions/3316113/why-do-i-have-to-use-this) – jAndy Sep 03 '10 at 06:48

7 Answers7

156

this is the DOM object, whereas $(this) is the jQuery wrapper around same.

When using this, you can call DOM methods on it, but not jQuery methods. When using $(this), you can call jQuery methods on it, but not DOM methods.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
10

$(this) - represent current DOM element on which event this function is called

The this keyword - In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • It helps to note that `$(this)` represents the DOM element wrapped as a jQuery object *because* and *when* `this` refers to the DOM element as a native DOM API object – sharat87 Sep 03 '10 at 05:46
3

In jQuery, this refers to the DOM object, and $(this) refers to the same object but with jQuery methods added

you can't call this.each() because each is not a DOM method, its a jquery method

you can call $(this).each() because $(this) returns a jquery object

Rino Raj
  • 6,264
  • 2
  • 27
  • 42
each
  • 31
  • 1
2

$(this) is the current object that was selected using a jQuery selector or event attached to the object.

so if you have $('#myelement').click(..... then $(this) referes to the element that was clicked on so that $(this).hide() hides that element.

griegs
  • 22,624
  • 33
  • 128
  • 205
2

Here are two articles that you may find helpful:

What is this? by Mike Alsup

jQuery's this: demystified by Remy Sharp

Alek Davis
  • 10,628
  • 2
  • 41
  • 53
1

in jQuery the $() notation is a shorthand for the jQuery selector, so if you say $(this) you are asking jQuery to re-select your object. Then you have the usual jQuery functions available.
Then, this is the object selected by the outer jQuery call (JavaScript).

xKobalt
  • 1,498
  • 2
  • 13
  • 19
Marco
  • 1,346
  • 8
  • 9
0

$(this) is a jQuery object and you can use the power and beauty of jQuery, but with 'this' keyword, one need to use native JavaScript.