When looping over a group of items using jquery selectors is there a way to find out how many items there are on the collection?
each() jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.
Use each: ' i ' is the postion in the array, obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well). $('. testimonial'). each(function(i, obj) { //test });
The most important functionality of jQuery is provided by it's Selectors. This tutorial will explain jQuery Selectors with simple examples covering all the three standard selectors.
If you're using chained syntax:
$(".class").each(function() { // ... });
...I don't think there's any (reasonable) way for the code within the each
function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index
.)
But it's easy enough to make the collection available to the function that you're calling in each
. Here's one way to do that:
var collection = $(".class"); collection.each(function() { // You can access `collection.length` here. });
As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach
. The arguments that get passed to forEach
's callback are the entry being visited (what jQuery gives you as this
and as the second argument), the index of that entry, and the array you called it on:
$(".class").get().forEach(function(entry, index, array) { // Here, array.length is the total number of items });
That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach
.
Or for that matter, give yourself a new tool:
// Loop through the jQuery set calling the callback: // loop(callback, thisArg); // Callback gets called with `this` set to `thisArg` unless `thisArg` // is falsey, in which case `this` will be the element being visited. // Arguments to callback are `element`, `index`, and `set`, where // `element` is the element being visited, `index` is its index in the // set, and `set` is the jQuery set `loop` was called on. // Callback's return value is ignored unless it's `=== false`, in which case // it stops the loop. $.fn.loop = function(callback, thisArg) { var me = this; return this.each(function(index, element) { return callback.call(thisArg || element, element, index, me); }); };
Usage:
$(".class").loop(function(element, index, set) { // Here, set.length is the length of the set });
Use the .length
property. It is not a function.
alert($('.class').length); // alerts a nonnegative number
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