GETELEMENTBYID AND ONLOAD USING JAVASCRIPT

Goti Bandu

Total Post:119

Points:835
Posted by  Goti Bandu
 1999  View(s)
Ratings:
Rate this:
Hi Mindstick!

HTML file ...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript" src="src/myJS.js"></script>

</head>

<body onload="myJS.myFunction();">

<p id="p01"></p>

</body>

</html>

External Javascript file (called myJS.js for convenience) ...

myJS = {

    myFunction: function()

    {

        //This works

        document.write("Hello world. ");

        //This does not work

        document.getElementById("p01").appendChild(document.createTextNode("Hello world, again"));

    }

};

My best guess is that the node p01 has not been created when myJS is executed, but I thought that onload would do the right thing with it.

thanks

  1. shreesh chandra shukla

    Post:105

    Points:735
    Re: getElementById and onLoad using javascript

    Hi!

    Because p01 is not yet added to the DOM. 

    Try like this: 

    <body>

    <p id="p01"></p>

    <script type="text/javascript">

    window.onload = myJS.myFunction;

    </script>

    </body>

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!