-1

I'm trying to make a simple "click this and make a number go up" button, but I get the error:

Uncaught TypeError: Unable to set property "innerHTML" in null

I've tried changing the order of some of the code, but it didn't work.

JS code:

var testCurrency = 0;
function addNumber(number){
  testCurrency += number;
}
document.getElementById("testCurrency").innerHTML = testCurrency;

HTML code:

<!DOCTYPE html>
<html>
  <head>
    <title>Yet Another Idle Game</title>
    <link rel="stylesheet" type="text/css" href="interface.css" />
  </head>
  <body>
    <button onclick="addNumber(1)">
    <script type="text/javascript" src="main.js"></script>
  </body>

Error:

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at addNumber (main.js:6)

I don't know how to make it work. The error appears as soon as I open the page. Can anyone help me? Thanks in advance!

Infinity
  • 23
  • 3
  • There appears to be no element in your html with id `testCurrency` – Anurag Srivastava Mar 24 '19 at 15:33
  • You don't have div with that id – Hien Nguyen Mar 24 '19 at 15:35
  • `document.getElementById("testCurrency").innerHTML` and `Cannot set property 'innerHTML' of null` means that `document.getElementById("testCurrency")` is `null` instead of a Node, so there is no such element in your HTML. this may mean that there is no such element at all (or mistake in the id string) or there is no such element yet, which means that you running your code before element was added (or html was built). – extempl Mar 24 '19 at 15:35
  • Where is the "testCurrency" in your body ??? PRefer to use TextContent instead of innerHTML – Mister Jojo Mar 24 '19 at 15:36

1 Answers1

0

If You use 'getElementById', those "Id" refer to HTML Id. So, in Your HTML u should have element with id="testCurrency". for example:

<body>
    <button onclick="addNumber(1)">
    <p> id="testCurrency"></p>
    <script type="text/javascript" src="main.js"></script>
</body>
  • + I would like to add, that it is better, to add eventListeners in JS than in HTML, so You should add some event listener to button. For example, You add to your button id ="someId", than in JS you add: document.getElementById("someId").addEventListener('click', function(event){ "here goes what to do if button is clicked, event variable contains object, that contains information about this event" } – Rafal Graniczny Mar 24 '19 at 15:40