Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're using chained syntax:</p> <pre><code>$(".class").each(function() { // ... }); </code></pre> <p>...I don't think there's any (reasonable) way for the code within the <code>each</code> function to know how many items there are. (<em>Unreasonable</em> ways would involve repeating the selector and using <code>index</code>.)</p> <p>But it's easy enough to make the collection available to the function that you're calling in <code>each</code>. Here's one way to do that:</p> <pre><code>var collection = $(".class"); collection.each(function() { // You can access `collection.length` here. }); </code></pre> <p>As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's <code>forEach</code>. The arguments that get passed to <code>forEach</code>'s callback are the entry being visited (what jQuery gives you as <code>this</code> and as the <em>second</em> argument), the index of that entry, and the array you called it on:</p> <pre><code>$(".class").get().forEach(function(entry, index, array) { // Here, array.length is the total number of items }); </code></pre> <p>That assumes an at least <em>vaguely</em> modern JavaScript engine and/or a shim for <code>Array#forEach</code>.</p> <p>Or for that matter, give yourself a new tool:</p> <pre><code>// 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); }); }; </code></pre> <p>Usage:</p> <pre><code>$(".class").loop(function(element, index, set) { // Here, set.length is the length of the set }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload