Hello everyone. )

There is a certain JS Code:
scripts.js

mysite={ addDiv: function() { var newDiv=document.createElement("div"); var div=document.getElementById("myDiv"); div.appendChild(newDiv); } } 

why in that case nothing works: somepage.html:

 .... <script> mysite.addDiv(); </script> <body> ... <div id="myDiv"></div> 

And in this, everything works:
....

 <body onload="mysite.addDiv()"> ... <div id="myDiv"></div> 

    2 answers 2

    In the first case, the script works until a div appears on the page, so it breaks off on trying to reach it. Move the script after the div # myDiv - everything will work.

    • damn right thank. ) - Eugene

    The rule of good tone is to place the scripts at the end of the page (if they are, of course, not necessary in the process of loading the page) in order to avoid such situations.

    And it would be good to hedge something like this:

    window.onload = function(){ // код инициализации }