March 25, 201511 yr This should be pretty basic, but I can't seem to get it right I am trying to sum multiple dynamic values and output the total for each parent div. My html is as the example below: <div class="parent"> <ul> <li><span class="count">0</span></li> <li><span class="count">1</span></li> <li><span class="count">4</span></li> <li><span class="count">0</span></li> </ul> <span class="total">0</span> </div> <div class="parent"> <ul> <li><span class="count">1</span></li> <li><span class="count">3</span></li> <li><span class="count">0</span></li> <li><span class="count">2</span></li> </ul> <span class="total">0</span> </div> JS: $('.parent').each(function(){ var sum = 0; var count = $(this).find('.count').text(); sum = +Number(count); $(this).find('.total').text(sum); console.log(sum) }); How do I iterate through each span.count and get its value? Hope that makes sense - thank you very much in advance! Edited March 25, 201511 yr by teodora
March 25, 201511 yr Try this: http://jsfiddle.net/ux0o8gqu/ $('.parent').each(function(){ var sum = 0; var counts = $(this).find('.count'); counts.each(function() { sum+= parseInt($(this).text()); }); console.log(sum); }); Edit: Forgot to add code! Edited March 25, 201511 yr by Lyndsey
March 25, 201511 yr This is the JavaScript jQuery you need: The .text function returns the result as a string so it needs to be converted to a number though the parseInt function. You also want to be looping through each individual count within the parent each loop, and incrementing the sum on each iteration. $('.parent').each(function(){ var sum = 0; $(this).find('.count').each(function(){ sum += parseInt($(this).text()); }); console.log(sum); }); Edit Lyndseys result posted while I was writing mine is pretty much the same Edited March 25, 201511 yr by rbrtsmith
Create an account or sign in to comment