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

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.

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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.