Search code examples
javascriptinnerhtmlparseintcalculation

Ignore certain characters in an innerHTML so I can use parseInt


I'm trying to copy the contents of an innerHTML on a webpage and calculate a number, then add that to the innerHTML, but they contain a $ which is messing up the calculation.

 var x = document.getElementsByClassName("item");
    var i;
    var counter;

    for (i = 0; i < x.length; i++) {
        counter += parseInt(x[i].innerHTML, 10);
        var j = Math.floor(counter/2.15); 
        x[i].innerHTML += (" " + j +"K");
    }


<div class="item">$25.00</div>

An example of the innerHTML would be $25.00 and I want to take that value and divide it by 2.15 and put it after the $25.00. EX: $25.00 11K

This code returns NaNK because the dollar sign ($), what can I do to make it be ignored or removed so the calculation can work? Also, I might not be using parseInt right.


Solution

  • You need to get a string containing only numerical value first for that remove the character $ using a regex.

    var x = document.getElementsByClassName("item");
        var i;
        var counter = 0;
    
        for (i = 0; i < x.length; i++) {
          
            var valueString  = x[i].innerHTML.replace(/[$]/g,"");
            counter += parseInt(valueString, 10);
            var j = Math.floor(counter/2.15); 
            x[i].innerHTML += (" " + j +"K");
        }
    <div class="item">$25.00</div>

    P.S : Do not forget to give counter an initial value 0 if you want to use +=