SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2010
    Posts
    34
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    innerHTML Not working!!

    I trying to display a random number using innerHTML
    Here's my code:
    HTML 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
    SitePoint Enthusiast
    Join Date
    Jun 2008
    Posts
    49
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb

    It does not work because at the moment you call the document.getElementById("myString") the "myString" is not defined. Try to put the javascript right before body tag, like this:

    HTML Code:
    <html>
    <head>
    </head>
    <body>
    <div id="myString"></div>
    <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>
    </body>


Bookmarks

Posting Permissions

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