Ton
Ton

Reputation: 199

What is $(0) and $(1) used for in jQuery?

While reading the following performance test, I noticed the author used $(0) and $(1). What is the purpose of this?

http://jsperf.com/scriptjunkie-premature-3

var $a = $(0);

function fn_1() {
 var $a = $(this);
 if ($a.attr("rel") == "foo") {
  $a.addClass("foo");
 }
 else {
  $a.addClass("other");
 }
}

function fn_2() {
 $a.context = $a[0] = this; // fake the collection object
 if ($a.attr("rel") == "foo") {
  $a.addClass("foo");
 }
 else {
  $a.addClass("other");
 }
}

Upvotes: 9

Views: 485

Answers (1)

Justin Ethier
Justin Ethier

Reputation: 134167

If you look at the jQuery source code, you can see that init is called when $() is executed. This function contains several if statements to handle various pieces of information passed as the selector. At the end of the function the following is called:

return jQuery.makeArray( selector, this );

If a number such as 1 or 2 is passed, the call to makeArray will just convert it to an array such as [1], [2], etc. So there is nothing particularly special about $(1).

Upvotes: 1

Related Questions