Get text from each element with certain class and then add up

Viewed 56

I'm trying to do some calculations using javascript. I'm basically getting the text of each element with a certain class, convert that to a number and then add those numbers up. This is what I've got so far:

<p class="item-size">1000</p>
<p class="item-size">2000</p>

JS:

$(document).ready(function(){
    var elements = document.getElementsByClassName("item-size");
    var size = ''
    for (var i=0; i<elements.length; i++) {
        size += parseInt((elements[i].innerText).replace(/[^0-9.]/g, ""));
    }
    console.log(size);
});

This returns 10002000 in the console. However, I need to get each of those values and then add them up instead of displaying them as one number. So the result should be 3000. I've tried this:

var myTotal = 0;
for(var i = 0, len = size.length; i < len; i++) {
    myTotal += size[i][1];  
    console.log(myTotal);
}

However, this returns NaN. Any ideas how to do this?

5 Answers

var size = 0, when you add string with integer it will return string and calculated as string. int + str = str


Here's ES5 version:

const elements = document.getElementsByClassName("item-size");
const size = Object.keys(elements)
    .reduce((acc, curr) =>
        acc + parseInt(elements[curr].innerText.replace(/[^0-9.]/g, "")), 0)
console.log(size);

https://jsfiddle.net/becg3vqu/3/

You need a number as target variable.

 $(document).ready(function(){
      var elements = document.getElementsByClassName("item-size");
      var size = 0; // <-- zero instead of an empty string
      for (var i=0; i<elements.length; i++) {
          size += parseInt((elements[i].innerText).replace(/[^0-9.]/g, ""), 10); // take base
      }
      console.log(size);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="item-size">1000</p>
<p class="item-size">2000</p>

Loop through all the children of an element and for each one increment a number by the textcontent of the element with a unary operator.

function getSumOfClass(className, root) {
  if (!(root instanceof HTMLElement)) root = document.body;
  return [].reduce.call(root.querySelectorAll("." + className),
    (result, dom) => result + (+dom.textContent || 0), 0);
}

console.log(getSumOfClass("item-size"));
<p class="item-not-size">500</p>
<p class="item-size">1000</p>
<p class="item-size">2000</p>

Adding a + or a - infront of a parameter or literal will convert it to a number. If it can't be converted to a number, the result will be NaN so you can just add an || operator to return a 0 in that case (so that the non arithmetic value will be ignored).

Using javascript vanilla

<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <p class="item-size">1000</p>
  <p class="item-size">2000</p>
  <script>
    //getting the texts that contain numbers
    let items = document.getElementsByClassName("item-size");
    let sum = 0;
    //Now for each element in the arrays
    for (let i = 0; i < items.length; i++) {
      sum = sum + parseInt(items[i].innerText);
    }
    console.log(sum);
  </script>
</body>

</html>

Since size is initially an empty string the addition wont work as you expected. Initialize var size to 0.

Related