0

I'm learning JS from "Professional Javascript for Web Developers" and I can't play with DOM tree because it doesn't seem to work.

Here's an example I'm testing locally:

http://jsfiddle.net/y5nfL/

It alerts "DIV" on jsfiddle, while locally I'm getting this in the console:

Uncaught TypeError: Cannot read property 'tagName' of null

Here's my index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>JS sandbox</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <div id="myDiv"></div>
    </body>
</html>

And script.js

var div = document.getElementById("myDiv");
alert(div.tagName);

What am I missing? I've been trying other stuff like cloning etc. but getElementById() also returns null every time...

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
Wordpressor
  • 5,847
  • 19
  • 58
  • 93

1 Answers1

4

When your script is executed the DOM doesn't contain anything after the script tag. You need to wait until the DOM is fully ready before trying to access it.

Another, even easier, option would be moving your script tag to the very end of the document, right before </body>.

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
  • 2
    Oh God, I'm so stupid :) Thanks a lot, moved the script right before body closing tag even before your edit. Thanks a lot! – Wordpressor Nov 29 '13 at 00:52
  • 1
    Sorry, just had to +1 that comment… ;-) – RobG Nov 29 '13 at 00:53
  • Haha, that's okay, my only excuse is - I'm still learning, after all, though I'm a bit disappointed that i couldn't figure it out on my own. – Wordpressor Nov 29 '13 at 00:55