1

So i have this empty page,

<html>
    <head>
        <title>JS</title>
        <script type="text/javascript">
            var container = document.getElementById("container");
            console.log(container);
        </script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

and for some reason console.log returns "null" instead of div object. But when i put code onto some website like jsfiddle, it works. How do i fix this, is it a common problem?

Mikiku
  • 152
  • 1
  • 12
  • 3
    Short answer is because your div doesn't exist yet. Your script code is run immediately, rather than waiting for the page to finish loading. – Paul Richter Dec 29 '13 at 00:12
  • If you put that exact code into jsfiddle, the console would output `null` (http://jsfiddle.net/Ruq8P/) so is that what you're expecting to get ? – adeneo Dec 29 '13 at 00:14
  • Also, [This stackoverflow answer](http://stackoverflow.com/a/8996894/877472) has some good information relating to script execution order which illustrates what I and vcsjones are talking about. – Paul Richter Dec 29 '13 at 00:19

1 Answers1

3

JSFiddle may not mimic DOM loading correctly. The problem with your example is your JavaScript is executed before the DOM is completely loaded. The DOM is loaded top-down, so when your JavaScript is executed, the container div doesn't exist in the DOM yet.

You can move your script block after your div, that's a quick way to resolve the issue. Alternatively, you can listen for an event for when the DOM is loaded, then execute your code. This StackOverflow question demonstrates how to do that.

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286