Need to convert .innerHTML result to javascript number

I have an 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 75 more numbers using .innerHTML . Then I would like to make the 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 the same as 40 3, etc .. I tried parseInt , parseFloat , .value , but the result was always NaN. Any suggestions?

+2
source share
2 answers

You need to initialize counter start number, otherwise you do the math on undefined .

 var counter = 0; 

And then in a loop use parseInt , parseFloat or direct number conversion to .innerHTML .

 var counter = 0; for (var i=0; i<features.length; i++){ counter += parseFloat(valuelements[i].innerHTML); } 

In a modern browser, you can do this:

 var count = [].reduce.call(valueelements, function(c, v) { return c + parseFloat(v.innerHTML); }, 0); 
+6
source

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; }); 
+3
source

Source: https://habr.com/ru/post/1268919/


All Articles