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>
精彩评论