Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is document.GetElementById returning null [duplicate]

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.

like image 547
BadDayComing Avatar asked Apr 13 '10 18:04

BadDayComing


People also ask

Why is my getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

What will method getElementById () return if nothing is found?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.

What does the document getElementById () method return?

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.


2 Answers

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.

like image 193
steve_c Avatar answered Oct 14 '22 09:10

steve_c


Try this:

 <script type="text/javascript">   window.onload = function() {    document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";   }  </script> 
like image 30
Sarfraz Avatar answered Oct 14 '22 08:10

Sarfraz