40

I've been using document.GetElementById() successfully but from some time on I can't make it work again. look at the following Code:

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

I am getting document.getElementById("parsedOutput") is null all the time now. It doesn't 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.

inetphantom
  • 2,001
  • 1
  • 29
  • 54
BadDayComing
  • 401
  • 1
  • 4
  • 3

6 Answers6

59

You can use the script tag like this:

<script defer>
    // your javascript code goes here
</script>

The JavaScript will apply to all elements after everything is loaded.

Patrick D'appollonio
  • 2,437
  • 1
  • 14
  • 33
steve_c
  • 5,933
  • 4
  • 28
  • 40
38

Try this:

 <script type="text/javascript">
  window.onload = function() {
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
  }
 </script>
Sarfraz
  • 355,543
  • 70
  • 511
  • 562
11

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
  • 4,690
  • 2
  • 28
  • 48
6

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
  • 180,104
  • 92
  • 446
  • 681
4

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
  • 9,453
  • 1
  • 22
  • 25
-2
<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.

Tarik
  • 73,061
  • 78
  • 222
  • 327