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?
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.
The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
The jQuery selector code returns an array by itself. No need to do anything with it.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With