Currently diving into the realm of JavaScript with the help of "Professional Javascript for Web Developers," but running into a roadblock when attempting to manipulate the DOM tree.
Testing out an example locally, which works perfectly fine on jsfiddle:
However, upon testing it locally, I'm encountering the following error in the console:
Uncaught TypeError: Cannot read property 'tagName' of null
My index.html file looks like this:
<!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>
Here's what my script.js file contains:
var div = document.getElementById("myDiv");
alert(div.tagName);
I've tried numerous other methods such as cloning elements, but still end up with getElementById() returning null every time. What could be causing this issue? Any insights would be greatly appreciated.