3

What is the difference between this and $(this) in jQuery? And when should I use which?

Sergio
  • 1,037
  • 1
  • 8
  • 5

3 Answers3

3
$('p').each(function () {
  //this.id;
  //$(this).attr('id');
})

If you consider the function above jQuery will loop through each paragraph element on the page and will return a reference to each paragraph element by passing the 'this' variable into the anonymous function. If the 'this' variable is wrapped in the jQuery function ($(this)) then we can access all the jQuery goodness in relation to the element e.g $(this).find('span'). The 'this' object on it's own is just a normal Javscript DOM Object.

ipr101
  • 24,096
  • 8
  • 59
  • 61
0

this returns a native JavaScript object (if I call it right), $(this) returns a jQuery object.

$(this)[0] == this
katspaugh
  • 17,449
  • 11
  • 66
  • 103
marrat
  • 534
  • 1
  • 6
  • 14
0

$() 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.

duplicate: jQuery: What's the difference between '$(this)' and 'this'?

Community
  • 1
  • 1
Mr.T.K
  • 2,318
  • 6
  • 26
  • 42