JQuery object array designation

I am new to jQuery and I have a little problem understanding its array notation for objects. By reading jQuery docs and this article , it seems like you can refer to the nth element in the object returned by the selector, doing something like

$('.foo')[n]; 

Correctly? Should I use jQuery manipulation functions / effects in tandem? Something like (this does not work for me)

 $('.foo')[0].hide(); 

I also tried, to no avail:

 var arr = $('.foo').get(); arr[0].hide(); 

Is there something wrong with my syntax? What is the best way to do what I'm trying to do here?

Thanks!

+8
jquery jquery-selectors
source share
2 answers

Array notation [0] and the .get() method return a reference to the DOM element inside the jQuery object, and you can Do not use jQuery methods for DOM elements.

Try the eq() method because it returns a new jQuery object:

 $('.foo').eq(0).hide(); 

Note also that using an array notation or .get() to get a reference to a DOM element means that you can directly access the properties of the DOM element, for example:

 var firstElId = $('.foo')[0].id; 

... with the second entry that $('.foo')[0] will be undefined and $('.foo')[0].id will $('.foo')[0].id error if there are no elements matching the '.foo' selector.

+17
source share

When you reference a jQuery object as an array, you return a DOM element. You will need to convert it back to a jQuery object in order to use methods like .hide ()

 var bar = $('.foo')[n]; var $bar = $(bar); $bar.hide(); 

Or just use the jQuery eq () method:

 var bar = $('.foo').eq(n); bar.hide(); 
+6
source share

All Articles