Why is document.GetElementById returning null

BadDayComing picture BadDayComing · Apr 13, 2010 · Viewed 95.9k times · Source

I've been using document.GetElementById succesfully but from some time on I can't make it work again. Old pages in which I used it still work but things as simple as this:

<html>
<head>
 <title>no title</title> 
 <script type="text/javascript">
 document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
 </script>
</head>
<body>
 <div id="ThisWillBeNull"></div>
</body>
</html>

Are giving me "document.getElementById("parsedOutput") is null" all the time now. It doesnt matter if I use Firefox or Chrome or which extensions i have enabled or what headers I use for the html, it's always null and I can't find what could be wrong.

Thanks for your input =)

Answer

steve_c picture steve_c · Apr 13, 2010

The page is rendered top to bottom. You code executes immediately after it's parsed. At the time of execution, the div does not exist yet. You need to wrap it in an window.onload function.