Javascript that accesses the DOM must not execute UNTIL the DOM has been loaded.
Code that runs in the <head>
section of the document will execute BEFORE the DOM has been loaded and thus if it tries to operate on the DOM, the DOM will simply be empty.
Code that runs in the <body>
section of the document will execute AFTER any DOM elements that are before that script tag, but BEFORE any DOM elements that are after the script tag.
If you put <script>
tags at the very end of the <body>
section right before the </body>
tag, then the whole DOM will be ready when that script executes.
DOMContentLoaded
(which jsFiddle calls onDomReady
) is an event that fires when the DOM is now loaded and is available for script to access. If you run your code when the DOMContentLoaded event fires, then the DOM will be ready for your code to access at that point.
window.onload
is an event that fires when the DOM is now loaded and any resources specified in the HTML of the page are also done loading (like images). This always fires after the DOMContentLoaded event.
You can see further description of this issue here: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
If code works when in the <body>
, but not in the <head>
, then you are probably running the code too early in the <head>
tag before the DOM is ready. You can either just leave it near the end of the <body>
or you can hook it up to one of the load events and then you can put it in the <head>
tag if you want.