zch
zch

Reputation: 3

"Uncaught TypeError" when executing a Javascript function from a <script> HTML tag

I'm working on a basic quiz Javascript game, but when I use

document.getElementById("demo").innerHTML = "text";

I get this error message:

Uncaught TypeError: Cannot set property 'innerHTML' of null

in the Chrome Console. I have no idea why this no longer works, it has worked for me in the past. However, if I open up a new tag, the function runs and the code works. It's only when I run the function in the same tag. My code is below:

<!DOCTYPE html>
<html>
<head>
    <title>Study Quiz</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script>
    function quiz() {
    var rnd = Math.floor(Math.random() * 4);
    document.getElementById("demo").innerHTML = rnd;
    }
    quiz(); //this one does not work
    </script>
</head>
<body>
<p id="qarea"><p>
<p id="demo"></p>
<script>
quiz(); //this one does work
</script>
</body>
</html>

Upvotes: 0

Views: 300

Answers (3)

inoabrian
inoabrian

Reputation: 3800

It should be the following. Where you would have to add the id attribute to the p tag.

<!DOCTYPE html>
<html>
<head>
    <title>Study Quiz</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script>
       function quiz() {
          var rnd = Math.floor(Math.random() * 4);
          document.getElementById("demo").innerHTML = rnd;
       }
       quiz(); // Will not work here because there is no such 
               // element with ID "demo" at this point in the page load.

    </script>
</head>
<body>
<p id = "qarea"><p>
<p id = "demo"></p>
<script>
   document.addEventListener( "DOMContentLoaded", function(){
      quiz(); // Will work here because the DOM is loaded at this point.
   });
</script>
</body>
</html>

Upvotes: -1

Alfredo Alvarez
Alfredo Alvarez

Reputation: 334

You forgot to include id in front of your ="demo" it should look like <p id="demo"> instead of <p="demo"></p>

Second the reason the first call to quiz does not work is that your document has not loaded yet. you want to do this on pure js

 <body onload="myFunction()">

Upvotes: 4

Istv&#225;n
Istv&#225;n

Reputation: 5127

Like this should work: http://jsfiddle.net/t8jnhmhg/1/ <p="demo" is wrong

Upvotes: 0

Related Questions