Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading all objects with class into an array using jQuery

Tags:

jquery

I have a bunch of div's on my page with class testClass.

I want to load them into an array and then check the array's size.

But its not working?

myArray = $('testClass');

alert(myArray.count);

What's wrong?

like image 474
user67033 Avatar asked Feb 16 '09 19:02

user67033


People also ask

How to traverse array 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.

What is each() in jQuery?

The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.

Does jQuery class selector return array?

The jQuery selector code returns an array by itself. No need to do anything with it.

How do you loop through an element with the same class in jQuery?

Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.


2 Answers

The code that you have provided returns an iterable jQuery object, but not an array. Also, you have made a mistake in your class selector.

For check the size of that jQuery object, you can use:

var $j_object = $(".testClass");
alert($j_object.size());

To loop over that object, you can use the each() function:

var $j_object = $(".testClass");
$j_object.each( function(i) { doSomethingHere(); } );

Check the jQuery documentation for more information on how to use each().

One other note. If you want to do something with the dom object within the each function, you can refer to 'this'. To get the jQuery object from the dom object, you can use $(this).

Also, the $ sign is completely optional, but can help to distinguish between jQuery objects and other variables, such as those that denote dom elements.

like image 67
jonstjohn Avatar answered Nov 03 '22 09:11

jonstjohn


You have:

myArray = $('testClass');
alert(myArray.count);

You want:

myArray = $('.testClass');
alert(myArray.length);

Notice, first, the . for testClass. Then, myArray is a JavaScript object, so you have access to the length key.

like image 41
leftnode Avatar answered Nov 03 '22 10:11

leftnode