Duplo W
Duplo W

Reputation: 623

Why does not this code work?

This code should work.. But it doesn't and I get an error message that says:

Uncaught TypeError: Cannot set property 'innerHTML' of null

It is not the first time I've gotten this error and I still don't understand it...

HTML:

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

<link rel="stylesheet" type="text/css" href="mycss.css">
<script src="myjavascript2.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>

<body>

<button onclick="myFunction()">Play</button>
<p id="test"></p>



</body>
</html>

javascript:

var things = ['rock','paper','scissors'];

function myFunction() {

var i = Math.floor(Math.random()*things.length));
document.getElementById("test"+(i+1)).innerHTML=things[i];
}

Upvotes: -1

Views: 95

Answers (3)

knrz
knrz

Reputation: 1811

If you want the single element to change the text, have this as your JavaScript:

document.getElementById("test").innerHTML=things[i];

If you want it go go into multiple elements, then in your HTML replace <p id="test"></p> with:

<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

The element referenced by your code does not exist in the DOM:

document.getElementById("test"+(i+1))

You have in your HTML:

<p id="test"></p>

Your code is looking for "test3"

Upvotes: 1

danfuzz
danfuzz

Reputation: 4353

It doesn't look like you have any elements with ids like test1, test2, etc.

Upvotes: 1

Related Questions