get a total of jquery's .each()

Viewed 58976

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;
});  
6 Answers

You can try this

const count = $('#accordion li').each(function() {
    // Do something
}).length;

It works because .each() returns a jQuery object which has a length property.

One of the big issues, which I have not found a fix for yet, is if you have two sets of the same thing you will iterate through.

For instance, 2 table heads that you are iterating through number of column headers. If you use length on ( $item.children().find('thead tr th').each... ) for your each clause and you have 2 tables it will double the amount of your length that you are trying to walk through potentially [5 column headers in each table will return length of 10].

You could do both on a id name and have those different but if adding dynamically then this can become a headache.

The only way I found once inside the foreach is to use $(this):

$item.children().find('thead tr th').each(function(i, th) {
  // I am working with a table but div could be used, or something else. 
  // I have 2 tables with 5 column headers, the below len return
  var len = $(this).closest('table').find('thead tr th').length;
  if (i < len) {
    // ...your code here
  }
});
Related