Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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");
 }
}
like image 759
Ton Avatar asked Mar 18 '12 02:03

Ton


People also ask

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.

What does 0 mean in jQuery?

It accesses the DOM element directly, without the jQuery wrapper.

What does $() short and stand for in jQuery?

$ is a short form of jQuery function. $() = jQuery() = window. $() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements.

When we should use $( this in jQuery?

The value of this inside a click event is a DOM element (the one that was clicked). Using $(this) converts it to a jQuery object. DOM elements do not have a hide() methods, but jQuery adds that and many other methods you can then call.


1 Answers

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

like image 105
Justin Ethier Avatar answered Oct 20 '22 00:10

Justin Ethier