views:

126

answers:

7

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 =)

+4  A: 

Timing.

The document isn't ready, when you're getting the element.

You have to wait until the document is ready, before retrieving the element.

Cheeso
+10  A: 

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.

steve_c
+2  A: 

Try this:

 <script type="text/javascript">
  window.onload = function() {
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
  }
 </script>
Sarfraz
+1  A: 

The browser is going to execute that script as soon as it finds it. At that point, the rest of the document hasn't loaded yet — there isn't any element with that id yet. If you run that code after that part of the document is loaded, it will work fine.

Syntactic
A: 

Wow, what can i say?

Thanks guys, so dam simple yet so hard to think about that in the first place!

BadDayComing
This should be a comment, not an answer.
Kevin Crowell
A: 

Without window.onload your script is never invoked. Javascript is an event based language so without an explicit event like onload, onclick, onmouseover, the scripts are not run.

<script type="text/javascript">  
  window.onload = function(){  
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";  
  }
</script>

Onload event:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

https://developer.mozilla.org/en/DOM/window.onload

Christopher Altman
A: 
<script type="text/javascript">
  window.onload += function() {
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
  }
 </script>

Use += to assign more eventHandlers to onload event of document.

Braveyard