7

How does the jQuery tag $(this) exactly work? I know how to use it, but how does jQuery know which element is 'active'? And what is the original Javascript tag for getting the current item, or is it jQuery only?

Konerak
  • 39,272
  • 12
  • 98
  • 118
Tim
  • 9,351
  • 1
  • 32
  • 48

4 Answers4

7

The this is a simple javascript (DOM) object, $(this) will turn the object into a jQuery object.

jQuery doesn't need to 'know' what this is, it doesn't treat this in a special way, no other than myHeaderDiv in

var myHeaderDiv = document.getElementById('header'); 
$myHeaderDiv = $(myheaderDiv); //just a variable transformed into jQuery object, as with this.
Konerak
  • 39,272
  • 12
  • 98
  • 118
4

this is context-dependent in jQuery (and JavaScript in general). It usually represents the current DOM element in a event handler, but is not a jQuery object.

$(this) is a jQuery object containing the current DOM element.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
4

The expression $(this) is just a regular Javascript function call, equivalent to jQuery(this). The this value is defined by Javascript itself, and is not a jQuery invention.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

Perhaps you should read about scope in JavaScript http://www.digital-web.com/articles/scope_in_javascript/

Mchl
  • 61,444
  • 9
  • 118
  • 120