title: JavaScript onload and DOM
body: <p>I have this example document:</p>
  
  <pre><code>&lt;html&gt;
      &lt;body&gt;
          &lt;script type="text/javascript"&gt;
              document.body.onload = myFunc();
  
              function myFunc() {
                  element = document.getElementById('myDiv');
                  element.innerHTML = 'Hello!';
              }
          &lt;/script&gt;
          &lt;div id="myDiv"&gt;&lt;/div&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Why 'element' is null if <code>myFunc</code> is a callback of <code>document.body.onload</code>?</p>
  
  <p>If, instead, the script is inserted after the div, it works:</p>
  
  <pre><code>&lt;html&gt;
      &lt;body&gt;
          &lt;div id="myDiv"&gt;&lt;/div&gt;
          &lt;script type="text/javascript"&gt;
              document.body.onload = myFunc();
  
              function myFunc() {
                  element = document.getElementById('myDiv');
                  element.innerHTML = 'Hello!';
              }
          &lt;/script&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>My question is: if I use the <code>onload</code> event within the handler function, should I have the entire DOM, or not? Why should I not?</p>