47

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.

1
  • In my case a web page created new id every time I restarted the web page. Commented Feb 9, 2022 at 22:12

6 Answers 6

67

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.

Sign up to request clarification or add additional context in comments.

Comments

43

Try this:

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

Comments

12

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

1 Comment

"without an explicit event [...] the scripts are not run" I disagree. If the scripts really did not run, then (1) Why did OP get the warning ... is null? (2) You'd have to specify the event in some way like <script event="...">...</script> because window.onload = ... is part of the script too and therefore would not run. ¶ I think this answer formulated the problem better.
7

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.

Comments

5

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.

Comments

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

1 Comment

This didn't do anything for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.