0

I'm trying to simply increment the number in a h1 tag by 100 when a button is clicked. I was able to get it to increment by 1 using the ++ operator but when I tried using the += operator to increment by 100 it places the value beside the initial one and does this every click, why is this happening?

Here is my code:

function Cash() {
    var x = document.getElementById("money").innerHTML;
    x += 100;

    document.getElementById("money").innerHTML = x;
}
<div class="col-6 balance">
   <h1 id="money" value="0">0</h1>
</div>
<button onclick="Cash()">Increase</button>
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
D0rzy
  • 3
  • 1
  • 2
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+%2B%2B+vs+%2B%3D) of [Javascript ++ vs +=1](https://stackoverflow.com/a/4397965/4642212). Also see [Difference between ++ and +=1 in javascript](https://stackoverflow.com/a/47682809/4642212). – Sebastian Simon Nov 27 '20 at 13:07

2 Answers2

0

The value you get from innerHTML is a string, so when you add (with +=) something to a string it connect the end of the original string.

Quick fix can be using Number method:

function Cash() {
    var x = Number(document.getElementById("money").innerHTML);
    x += 100;
    document.getElementById("money").innerHTML = x;
}
<div class="col-6 balance">
   <h1 id="money" value="0">0</h1>
</div>
<button onclick="Cash()">Increase</button>
A. Meshu
  • 4,053
  • 2
  • 20
  • 34
0

The reason you're not getting the expected results using += is due to both innerHTML and innerText returning a string and not a number. so your code is doing '0'+'100' as it's casting the 100 to a string. if you convert to a number before the add things will work as expected.

function cash() {
    var x = document.getElementById("money").innerText;
    x = parseInt(x, 10);
    x += 100;

    document.getElementById("money").innerHTML = x;
}

cash()
<div class="col-6 balance">
   <h1 id="money" value="0">0</h1>
</div>
denov
  • 11,180
  • 2
  • 27
  • 43