Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to convert result of .innerHTML to number on javascript

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?

like image 557
user2027553 Avatar asked Jan 31 '13 01:01

user2027553


2 Answers

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);
like image 71
the system Avatar answered Oct 11 '22 19:10

the system


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; });
like image 35
elclanrs Avatar answered Oct 11 '22 18:10

elclanrs