jahrichie
jahrichie

Reputation: 1235

jquery Calculate sum from elements markup

I have the child count coming from the server, i'd rather not do any more math there. I'd like to extract the number from the markup.

Within every .active-parent I need to loop through, and get a number from .category-count .

      children_counts = $('.active-parent .category-count')
      children_counts.each(function(){
        var parent_count = $(this).text();
        console.log(parent_count)
      });

I have it returning the numbers with the log statement

189
5
86
261

Can't figure out how to sum those up. Any help would be much appreciated.

Upvotes: 1

Views: 79

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

Initialize a variable and use parseInt to add the count inside the each loop.

children_counts = $('.active-parent .category-count');
var totalCount = 0;
children_counts.each(function(){
   var parent_count = $(this).text();
   totalCount += parseInt(parent_count, 10);
});
console.log('Total Count is -- ' + totalCount );

Upvotes: 2

Related Questions