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. So I made the following For Loop:
var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
var totaalPersonen = totaalPersonen + i;
alert(totaalPersonen);
}
However, the 3 and 2 are text, so I get Nan in the alerts. My question: how can in convert the 3 and 2 into strings so that I can make a sum of these values?
I tried with String(i)
but couldn't get it to work.
You need to convert the content of the DOM
element to a Number
. Then, you can use reduce
in order to calculate the sum.
const spans = document.querySelectorAll('#aantallen span'); const result = Array.from(spans).reduce((sum, spanElm) => sum + Number(spanElm.textContent), 0) console.log(result);
<div id="aantallen"> <span>3</span> <span>2</span> </div>
To convert string to Int in Javascript, Use:
parseInt(totaalPersonen);
You are reintializing var totaalPersonen = totaalPersonen + i;
in every loop. So you need to initialize totaalPersonen
outside the loop like this var totaalPersonen = 0;
and inside the loop just count it up like totaalPersonen = totaalPersonen + 1;
or just totaalPerseonen++;
Try this Assuming you are wanting to add the text inside the spans I have used innerHTML
, and not i
. Also, the totaalPersonen
variable should be declared outside the for loop otherwise it will be reinitialized each time.
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].innerHTML));
totaalPersonen = parseInt(totaalPersonen) + parseInt(spans[i].innerHTML);
//alert(totaalPersonen);
}
alert(totaalPersonen);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.