So I had an idea to let the computer guess the number with JavaScript as code language. I know exactly what it must do, but it isn't doing it. The idea is (to see if it works) to get a random number between 1 and 100, when you open the webpage. Weird thing, is that if I call the function in the same JavaScript file it gives an error, but if I call the function with a HTML button, it's working totally fine! The F12-console gives the following error:
Unable to set property 'innerHTML' of undefined or null reference
I have the following code:
var guessTheNumber = function() {
// var number = prompt("Tell me a number between 1 and 100.");
var x = document.getElementById("JS1");
x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
guessTheNumber();
<!DOCTYPE html>
<html>
<head>
<title>JS test</title>
<script type="text/javascript" src="JavaScript.js"></script>
</head>
<body>
<button onclick="guessTheNumber()"></button>
<p class="test">test</p>
<p id="JS1"></p>
</body>
</html>
I tried Microsoft Edge and Google Chrome as browsers, no results. I do not know what I am doing wrong, so any help is appreciated!