Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Object array notation

I'm new to jQuery, and I'm having a little trouble understanding its array notation for objects. Reading the jQuery docs and this article, it seems that you can refer to the nth item in an object returned by a selector by doing something like

$('.foo')[n];

Correct? Should I be able to use jQuery manipulation/effects functions in tandem? Something like (this isn't working for me)

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

I've also tried, to no avail:

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

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

Thanks!

like image 603
Jared Roder Avatar asked Dec 08 '12 04:12

Jared Roder


People also ask

How do I iterate an array of objects in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How can you use array with jQuery?

Syntax And Declaration: var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array. Iteration Approach using JQuery: jQuery provides a generic .

What is array in jQuery?

jQuery array is used to store multiple objects/values in a single array variable.

Can we use forEach loop in jQuery?

forEach() methods. There are also libraries like foreach which let you iterate over the key value pairs of either an array-like object or a dictionary-like object. Remember: $. each() and $(selector).


2 Answers

The [0] array notation and the .get() method both return a reference to a DOM element within the jQuery object, and you can't use jQuery methods on DOM elements.

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

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

Note also that having used the array notation or .get() to get a reference to a DOM element means you can then get direct access to the DOM element's properties, e.g.:

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

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

like image 56
nnnnnn Avatar answered Oct 13 '22 01:10

nnnnnn


When you reference a jQuery object as an array you get a DOM element back. You'll need to convert it back to a jQuery object to use methods like .hide()

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

$bar.hide();

Or just use jQuery's eq() method:

var bar = $('.foo').eq(n);
bar.hide();
like image 21
Thomas Higginbotham Avatar answered Oct 13 '22 03:10

Thomas Higginbotham