views:

71

answers:

3

Hi,

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;
});  
+4  A: 
$('#accordion li').length;
Colin
+11  A: 

Two options:

$('#accordian li').size(); // the jQuery way
$('#accordian li').length; // the Javascript way, which jQuery calls anyhow....

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

Owen
The jQuery docs actually recommend using `length`, not `size()`: see the comment at http://api.jquery.com/size/
tvanfosson
+1 - `length` ftw
Russ Cam
Yeah I just didn't like the repition of the jquery selector...once for the each() and then again for the size(). I've just assigned $('#accordion li') to a var now and called that twice.
elduderino
+3  A: 

Well, I just saw this question, and you already accepted an answer, but I'm going to leave one anyway.

The point of the question seems to be concerned with incrementing a counter.

The fact is that jQuery's .each() method takes care of this for you. The first parameter for .each() is an incrementing counter, so you don't need to do it yourself.

$('#accordian li').each(function(index) {
       // index has the count of the current iteration
    console.log( index );
});

So as you can see, there is an elegant solution built in for you.

patrick dw
Hi, Thanks for the reply. I actually need the total count. I know index gives me the incrementing counter but I need the total count of all matched list items.
elduderino