A Flash Developer Resource Site

Results 1 to 2 of 2

Thread: Confused with innerHTML

  1. #1
    Junior Member
    Join Date
    Jun 2010
    Posts
    20

    Confused with innerHTML

    I trying to display a random number using innerHTML
    Here's my code:
    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

  2. #2
    Senior Member
    Join Date
    Apr 2002
    Posts
    2,849
    Your browser reads HTML from top to bottom, and runs any Javascript it finds as it goes. When it runs document.getElementById("myString"), myString doesn't exist yet, because it hasn't read that far down the page.

    To fix it, either put the javascript at the end of your page (often recommended for performance), or wait for the page to be done loading. An easy way to do that is:

    Code:
    window.onload=function(){
        document.getElementById("myString").innerHTML = myArray[num];
    };

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center