Search code examples
javascriptfor-loopsuminternet-explorer-10

Sum of span values in For loop (working in IE10)


I have the following values within span tags:

<div id="aantallen">
 <span>3</span>
 <span>2</span>
</div>

In JS I want to get the sum of these values. I have this code to do it (which works, ... but):

const spans = document.querySelectorAll('#aantallen span');

const result = Array.from(spans).reduce((sum, spanElm) => sum + Number(spanElm.textContent), 0)

However, this code is not working in Internet Explorer 10 (and probably older versions) because ECMA 6 arrow is not supported.

Now I'm trying to code something that will also work in IE but I don't quite get it yet. I do have a version where I can use the texts in the spans but I can't get it to convert to integers because I get NaN errors:

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
console.log(spans);
var totaalPersonen = 0;
for(i=0;i<spans.length;i++)
{
    alert(parseInt(spans[i]));
    totaalPersonen = parseInt(totaalPersonen) +parseInt(spans[i]);
    //alert(totaalPersonen);
}
alert(totaalPersonen);

How can I convert the span values to integers and make a sum of them?


Solution

  • You are accessing spans directly and trying to add them up; instead you have to access the content within the span.

    Check the following snippet:

    var div = document.getElementById("aantallen");
    var spans = div.querySelectorAll("span");
    
    var totaalPersonen = 0;
    for(i=0;i<spans.length;i++)
    {
       const content = Number(spans[i].innerHTML)
        alert(content);
        totaalPersonen = Number(totaalPersonen) +content;
        alert(totaalPersonen);
    }
    <div id="aantallen">
     <span>3</span>
     <span>2</span>
    </div>