0

Why is an index of 0 used in the code below?

var $one = $('#one')[0];

Why not just use var $one = $('#one'); ?

REFERENCE

I found the above code while reading jQuery, how to use multiple cached elements

Community
  • 1
  • 1
TryHarder
  • 2,704
  • 8
  • 47
  • 65

3 Answers3

1

That's because $('#one') is a jQuery object, which is an "array-like" object containing your element. Since a jQuery object is an "array-like" object, adding the [0] retrieves the first and only element in the object.

As for optimization, operating on selectors makes jQuery (or Sizzle to be exact) run through the DOM and look for that one and only element in the DOM. Imagine that happening every time you do:

$('#one')

That's why, instead of operating on selectors and running through the DOM everytime, they cached the DOM element instead. You can easily recreate jQuery objects using existing references of elements, which isn't that much of a overhead compared to running through the DOM again.

var one = $('#one')[0]

// or synonymously
var one = document.getElementById('one');

// No running anymore through the DOM in search for "one" because jQuery simply
// uses this reference instead.
var theOne = $(one);

//Another jQuery object, but uses the same "one" fetched earlier
var anotherOne = $(one); 
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

They are not equivalent.

var $one = $('#one')[0];

Caches the first DOM node matching the selector #one. In order to convert this back to a jQuery object, you would need to do $($one) in order to use any jQuery functions, e.g. $($one).addClass("example");.

var $one = $('#one');

Caches the jQuery object, so you could call: $one.addClass("example");

Which one is right depends on the requirements for the $one object and how it is used.

jsFiddle for the above.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
1

var $one = $('#one')[0]; will return the actual DOM element

var $one = $('#one'); will return the wrapped jQuery object.

kcak11
  • 832
  • 7
  • 19