0

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!

Brent Meeusen
  • 179
  • 1
  • 11

3 Answers3

5

The problem is that the javascript file is loaded BEFORE the DOM, so the document.getElementById("JS1"); would be undefined.

To easily fix this, load the <script> at the BOTTOM of the <body> tag:

<!DOCTYPE html>
<html>
<head>
    <title>JS test</title>


</head>
<body>
    <button onclick="guessTheNumber()"></button>
    <p class="test">test</p>
    <p id="JS1"></p>

<script type="text/javascript" src="JavaScript.js"></script>
</body>
</html>
frozen
  • 2,114
  • 14
  • 33
1
<script>
// self executing function here
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);
}
(function() {

   // your page initialization code here
   // the DOM will be available here
   guessTheNumber();
})();
</script>

You have to wait until the dom is ready.

Also never declare your script in the head move your script tag below body.

jdmdevdotnet
  • 1
  • 2
  • 19
  • 50
0

try like this (without jQuery):

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);
}
document.addEventListener('DOMContentLoaded', function(){ 
    guessTheNumber();
}, false);
Pascalz
  • 2,348
  • 1
  • 24
  • 25