0

what's the easiest way to sum values who all are in the same class

<div class='head'>
  <div class='title'>
    <div class='sumMe'>$1.01</div>
  </div>
</div>

<div class='head'>
  <div class='title'>
    <div class='sumMe'>$2.01</div>
  </div>
</div>

sumMe = 3.02

1
  • How would you specify parents to make sure you are going down the right hiearchy? Commented Jul 27, 2011 at 13:11

3 Answers 3

4

You can achieve this quickly using a jQuery each loop, the Number() function, and the isNan() function just to be on the safe-side.

var sum = 0;

$(".sumMe").each(function(){
   var value = Number($(this).text());
   // or parseInt($(this).text(), 10);
   sum += isNaN(value) ? 0 : value;
});

alert(sum);
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I was going to write. You should add the base (10) to your parseInt call though, since for certain numbers you'll get odd results otherwise (it guesses the base)
updated OP if i may, what if it's a float, do i still need the radix? Will i have to manually strip dollar sign?
1

Try this:

var sumMeTotal = 0;
$(".sumMe").each(function(){
     //Use parseInt with a radix 10 
    var sumMe = parseInt($(this).text(), 10);
    sumMeTotal += sumMe;
});
alert(sumMeTotal);

Comments

1
var sum = 0;

$(".sumMe").each(function(){
   sum += +($(this).html());
});

alert(sum);

check working example here http://jsfiddle.net/RU8bm/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.