1

When I press get money, it will add [object HTMLDivElement]1 instead of just 1. this is the code:

<script>
    function cash(){
        var Cash = 0
        document.getElementById("Cash").textContent = Cash
    }
        function text(){
            Cash = Cash + Number(1)
            document.getElementById("Cash").textContent = Cash
        }
    </script>
</head>

<body onload="cash()">
    <div id="Cash"></div>
    <button class="button-long" onclick="text()">Get Money</button>
</body>

I do not know what is happening and I have found nothing else on how to fix this. The CSS has nothing to do with it, I have checked the code many times and changed and tested a lot of times as well and I have found nothing on this website or any other website about this. I would like some help on this one as I do not know what is happening.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175

1 Answers1

0

You declared the Cash variable inside the cash function, which is not visible to the text function. To fix this, you need to move the Cash declaration outside the cash function where is becomes visible to both function as follows:

<head>  
  <script>
    var Cash = 0

    function cash(){
      document.getElementById("Cash").textContent = Cash
    }

    function text(){
      Cash = Cash + Number(1)
      document.getElementById("Cash").textContent = Cash
    }
  </script>
</head>

<body onload="cash()">
    <div id="Cash"></div>
    <button class="button-long" onclick="text()">Get Money</button>
</body>

Given that Cash was not visible to the text function, you may now be wondering why you observed [object HTMLDivElement] for the value of Cash inside the text function instead of undefined. The reason for that is because you also have an element in the DOM with an id of the same name, i.e. Cash, which becomes a global property in the document. By declaring var Cash = 0 globally, that will shadow the Cash reference to the DOM element.

Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50