0

I trying to display a random number using innerHTML
Here's my code:

<html>
<head>
<script language="JavaScript">
var myArray = new Array("String1", "String2", "String3", "String4", "String5", "String6", "String7", "String8", "String9", "String10");

var num = Math.floor(myArray.length * Math.random());

document.writeln(myArray[num]);
//document.getElementById("myString").innerHTML = myArray[num];
</script>
</head>


<body>
<div id="myString"></div>
</body>
</html>

it works when I use document.writeln(myArray[num]); but does NOT work for document.getElementById("myString").innerHTML = myArray[num];

any ideas??
tks

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by MartinRinehart
0

It doesn't work with "getElementById()" function because the function is being called before your dom is built (and page is not rendered yet). As a result, the function throws an error because the div element with ID "myString" doesn't exist at the point when the function is being called.

The writeln() function is a function to add the content of the argument to the document (body tag). As a result, it waits until a body tag is created before it attempts to add the content.

If you want to use document.getElementById(), you need to call it under, in, or on the element you are creating.

// For example...
...
<body>
  <div id="myString"></div>
  <script type="text/javascript">
  document.getElementById("myString").innerHTML = myArray[num]
  </script>
</body>
...

// or
...
<body>
  <div id="myString">
  <script type="text/javascript">
  document.getElementById("myString").innerHTML = myArray[num]
  </script>
  </div>
</body>
...

// or (not really sure about the syntax in this case because I rarely use it)
...
<body>
  <div id="myString" onclick="javascript:document.getElementById('myString').innerHTML=myArray[num]">
  &nbsp;&nbsp;
  </div>
</body>
...

You could also use getElementById() inside a function which will be called later after the page is loaded.

Edited by Taywin: n/a

0

Yahoo guru (now Google guru) Steve Souders, in High Performance recommends always placing your script at the end of the body section. I'm sure he knows more than almost anyone about script performance.

In addition to the performance, it also fixes this bug as pointed out in the above reply. Script doesn't belong in the <head> (though that used to be where people put it).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.