I have a html that contains tables like the following example
<td class="topiccell">
<span class="topicnormal">
<a class="value" href="/topic/?lang=en&action=viewtopic&topic=http%3A%2F%2Fwww.wandora.org%2Fsparql%2Fresultset%2Fliteral%2F40">
40
</a>
</span>
</td>
<td class="topiccell">
<span class="topicnormal">
<a class="value" href="/topic/?lang=en&action=viewtopic&topic=http%3A%2F%2Fwww.wandora.org%2Fsparql%2Fresultset%2Fliteral%2F40">
3
</a>
</span>
</td>
and I need to parse 40, 3 and another 75 numbers using .innerHTML
. Then I would like to make a sum of all 75 numbers. I used the following
var valuelements = document.getElementsByClassName("value");
var features = new Array(valuelements.length);
for (var i=0; i<=features.length; i++){
var val = valuelements[i].innerHTML;
var counter = counter + val;
}
document.write(counter);
and the result was like 40 3 etc.... tried parseInt
, parseFloat
, .value
but the result always was NaN.
Any suggestions?
You need to initialize counter
with a starting number, otherwise you're performing math on undefined
.
var counter = 0;
And then in the loop, use parseInt
, parseFloat
, or a direct number conversion on the .innerHTML
value.
var counter = 0;
for (var i=0; i<features.length; i++){
counter += parseFloat(valuelements[i].innerHTML);
}
In a modern browser, you could do this:
var count = [].reduce.call(valueelements, function(c, v) {
return c + parseFloat(v.innerHTML);
}, 0);
Try something like this, using a more functional approach:
var sum = [].map.call(valuelements, function(v) {
return +v.textContent; }).reduce(function(a, b) { return a + b; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With