Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a total of jquery's .each()

I'm using jquery's .each() to iterate over a group of li's. I need a total of all the li's matched. Is the only way to create a count variable outside the .each() and increment this inside the .each()? It doesn't seem very elegant.

var count; $('#accordion li').each(function() {     ++count; });   
like image 599
Mike Rifgin Avatar asked Jul 27 '10 21:07

Mike Rifgin


People also ask

What is the use of each () function in jQuery?

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.

How do I get out of each loop in jQuery?

You can stop the loop from within the callback function by returning false . $( this ). addClass( "foo" ); });

How do you use each function in Javascript?

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.

Can we use foreach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.


1 Answers

Two options:

$('#accordion li').size(); // the jQuery way $('#accordion li').length; // the Javascript way, which jQuery uses 

Since jQuery calls length under the hood, it's faster to use that instead of the size() call.

like image 153
Owen Avatar answered Oct 05 '22 13:10

Owen