开发者

Why can't javascript find a div that is defined below it? [duplicate]

This question already has answers here: Why does jQuery or a DOM method such as getElementById not find the element? (6 answers) Closed 6 years ago.

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 thi开发者_StackOverflow社区s work? Thanks!!! (and yes, I want the div below the script)


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜