2

This works:

  <html>
  <body>
  <div id="bla"></div>

  <script type="text/javascript">
     var mybla = document.getElementById('bla')
  </script>

  </body>
  </html>

This doesn't:

  <html>
  <body>

  <script type="text/javascript">
     var mybla = document.getElementById('bla')
  </script>

  <div id="bla"></div>

  </body>
  </html>

mybla is null at this point. argh. How can I make this work? Thanks!!! (and yes, I want the div below the script)

Shai UI
  • 45,518
  • 63
  • 187
  • 278

1 Answers1

13

Because the DOM isn't fully loaded yet. You need to put your code in an onload handler if you want it above the HTML. Like this:

<script type="text/javascript">
    window.onload = function() {
        var mybla = document.getElementById('bla');
    }
</script>
Wayne
  • 56,476
  • 13
  • 125
  • 118