Cannot set property 'innerHTML' of null

JavascriptOnloadInnerhtml

Javascript Problem Overview


Why do I get an error or Uncaught TypeError: Cannot set property 'innerHTML' of null? I thought I understood innerHTML and had it working before.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>

<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>

</head>

<body>
<div id="hello"></div>
</body>
</html>

Javascript Solutions


Solution 1 - Javascript

You have to place the hello div before the script, so that it exists when the script is loaded.

Solution 2 - Javascript

Let us first try to understand the root cause as to why it is happening in first place.

> Why do I get an error or Uncaught TypeError: Cannot set property > 'innerHTML' of null?

The browser always loads the entire HTML DOM from top to bottom. Any JavaScript code written inside the script tags (present in head section of your HTML file) gets executed by the browser rendering engine even before your whole DOM (various HTML element tags present within body tag) is loaded. The scripts present in head tag are trying to access an element having id hello even before it has actually been rendered in the DOM. So obviously, JavaScript failed to see the element and hence you end up seeing the null reference error.

> How can you make it work as before?

You want to show the hi message on the page as soon as the user lands on your page for the first time. So you need to hook up your code at a point when you are completely sure of the fact that DOM is fully loaded and the hello id element is accessible/available. It is achievable in two ways:

  1. Reorder your scripts: This way your scripts get fired only after the DOM containing your hello id element is already loaded. You can achieve it by simply moving the script tag after all the DOM elements i.e. at the bottom where body tag is ending. Since rendering happens from top to bottom so your scripts get executed in the end and you face no error.

    Untitled Document

    <body>
        <div id="hello"></div>
        <script type ="text/javascript">
            what();
            function what(){
                document.getElementById('hello').innerHTML = 'hi';
            };
        </script>
    </body>
    

  2. Use event hooking: Browser's rendering engine provides an event based hook through window.onload event which gives you the hint that browser has finished loading the DOM. So by the time when this event gets fired, you can be rest assured that your element with id hello already loaded in the DOM and any JavaScript fired thereafter which tries to access this element will not fail. So you do something like below code snippet. Please note that in this case, your script works even though it is present at the top of your HTML document inside the head tag.

    Untitled Document

Solution 3 - Javascript

You could tell javascript to perform the action "onload"... Try with this:

<script type ="text/javascript">
window.onload = function what(){
document.getElementById('hello').innerHTML = 'hi';
};
</script>

Solution 4 - Javascript

Just put your JS in window.onload

window.onload = function() {

        what();

        function what() {
            document.getElementById('hello').innerHTML = 'hi';
        };

    }

Solution 5 - Javascript

The JavaScript part needs to run once the page is loaded, therefore it is advised to place JavaScript script at the end of the body tag.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>  
</body>
</html>

Solution 6 - Javascript

Javascript looks good. Try to run it after the the div has loaded. Try to run only when the document is ready. $(document).ready in jquery.

Solution 7 - Javascript

Here Is my snippet try it. I hope it will helpfull for u.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>

<body>
  
<div id="hello"></div>
  
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>
</body>
</html>

Solution 8 - Javascript

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example</title>

</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = '<p>hi</p>';
    };
</script>  
</body>
</html>

Solution 9 - Javascript

You could try using the setTimeout method to make sure your html loads first.

Solution 10 - Javascript

The root cause is: HTML on a page have to loaded before javascript code. Resolving in 2 ways:

  1. Allow HTML load before the js code.

    //or set time out like this:

  2. Move js code under HTML code

Solution 11 - Javascript

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>
</body>
</html>

Solution 12 - Javascript

I have had the same problem and it turns out that the null error was because I had not saved the html I was working with.

If the element referred to has not been saved once the page is loaded is 'null', because the document does not contain it at the time of load. Using window.onload also helps debugging.

I hope this was useful to you.

Solution 13 - Javascript

This error can appear even if you load your script after the html render is finished. In this given example your code

<div id="hello"></div>

has no value inside the div. So the error is raised, because there is no value to change inside. It should have been

<div id="hello">Some random text to change</div>

then.

Solution 14 - Javascript

You need to change div into p. Technically innerHTML means it is inside the <??? id=""></???> part.

Change:

<div id="hello"></div>

into

<p id="hello"></p>

Doing:

document.getElementById('hello').innerHTML = 'hi';

will turn

<div id="hello"></div> into this <div id="hello">hi</div>

which actually does not make sense.

You can also try to change:

document.getElementById('hello').innerHTML = 'hi';

into this

document.getElementById('hello').innerHTML='<p> hi </p> ';

to make it work.

Solution 15 - Javascript

Add jquery into < head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

Use $document.ready() : the code can be in < head> or in a separate file like main.js

  1. using js in same file (add this in the < head>):

  2. using some other file like main.js (add this in the < head>):

and add the code in main.js file :)

Solution 16 - Javascript

The error is self-explaining it is not getting the HTML tag in which You want to set the Data So make tag available to JS then only You can set Data to that.

Solution 17 - Javascript

No doubt, most of the answers here are correct, but you can also do this:

document.addEventListener('DOMContentLoaded', function what() {
   document.getElementById('hello').innerHTML = 'hi';  
});

Solution 18 - Javascript

There are different possible cause as discussed would just like to add this for someone who might have the same issue as mine.

In my case I had a missing close div as shown below

   <!DOCTYPE HTML>
   <html>
   <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Untitled Document</title>
   </head>
   <body>
   <div> //I am an open div
    <div id="hello"></div>
   <script type ="text/javascript">
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
   </script>
   </body>
   </html>

Missing a close div can result in disorganization of the transversal from child to parent or parent to child hence resulting in an error when you try to access an element in the DOM

Solution 19 - Javascript

Let the DOM load. To do something in the DOM you have to Load it first. In your case You have to load the <div> tag first. then you have something to modify. if you load the js first then that function is looking your HTML to do what you asked to do, but when that time your HTML is loading and your function cant find the HTML. So you can put the script in the bottom of the page. inside <body> tag then the function can access the <div> Because DOM is already loaded the time you hit the script.

Solution 20 - Javascript

> I have moved my <script> tag below the <body> tag. Let’s try

<body>
	<p>The time is <span id="time"></span>.</p>
</body>

<script>
// Allways keep script at end for date and time object //

	var d = new Date();

	document.getElementById("time").innerHTML = d;
	
</script>

Solution 21 - Javascript

This happened to me when using Django template tags on an if-check to see if there was a value available for a field - if no value I removed everything associated with the value from the page to keep things neat The only problem was the content I removed included the div and id I was trying to work with! If there was a value present there was no issue as the div that contained the id I was working with was present. If there was no value I received the error. Once it hit me that's what was going on then easy fix to just add the div in there if the if-check is false.

Before

{% if model.value %}
<div id='my-id'>{{model.value}}</div>
{% endif %}

After

{% if model.value %}
<div>{{model.value}}</div>
{% else %}
<div id='my-id'></div>
{% endif %}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshua WView Question on Stackoverflow
Solution 1 - JavascriptErik GodardView Answer on Stackoverflow
Solution 2 - JavascriptRBTView Answer on Stackoverflow
Solution 3 - JavascriptColyn1337View Answer on Stackoverflow
Solution 4 - JavascriptRIYAJ KHANView Answer on Stackoverflow
Solution 5 - Javascriptuser5323957View Answer on Stackoverflow
Solution 6 - JavascriptJT NolanView Answer on Stackoverflow
Solution 7 - Javascriptuser4909217View Answer on Stackoverflow
Solution 8 - Javascriptuser6175882View Answer on Stackoverflow
Solution 9 - JavascriptEddyView Answer on Stackoverflow
Solution 10 - JavascriptPines TranView Answer on Stackoverflow
Solution 11 - Javascriptuser2114253View Answer on Stackoverflow
Solution 12 - JavascriptPlaganomicsView Answer on Stackoverflow
Solution 13 - JavascriptMarko SlijepčevićView Answer on Stackoverflow
Solution 14 - Javascriptuser6175882View Answer on Stackoverflow
Solution 15 - Javascriptabe312View Answer on Stackoverflow
Solution 16 - JavascriptShubhamView Answer on Stackoverflow
Solution 17 - JavascriptShrey TripathiView Answer on Stackoverflow
Solution 18 - JavascriptElizabethView Answer on Stackoverflow
Solution 19 - JavascriptHeshanHHView Answer on Stackoverflow
Solution 20 - JavascriptDilip Kumar ChoudharyView Answer on Stackoverflow
Solution 21 - Javascriptblueblob26View Answer on Stackoverflow