111

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>
PherricOxide
  • 13,861
  • 1
  • 25
  • 41
Joshua W
  • 1,177
  • 2
  • 10
  • 15

20 Answers20

194

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

RBT
  • 18,275
  • 13
  • 127
  • 181
Erik Godard
  • 5,410
  • 6
  • 26
  • 32
52

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.

    <!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>
  1. 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 hello id 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.

<!DOCTYPE HTML>
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Untitled Document</title>
        <script type ="text/javascript">
            window.onload = function() {
            what();
            function what(){
                document.getElementById('hello').innerHTML = 'hi';
            };
        }
        </script>
        </head>
        
        <body>
        <div id="hello"></div>
        </body>
        </html>
RBT
  • 18,275
  • 13
  • 127
  • 181
  • Good stuff, but i'd add, I don't think the function that does document.getElementById(..).innerHTML . needs to be put within the onload. As that can load before the DOM loads and there's no error. Only its call needs to be.https://jsfiddle.net/fbz6wLpd/8/ – barlop Jul 26 '19 at 14:30
40

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>
Colyn1337
  • 1,443
  • 2
  • 17
  • 27
12

Just put your JS in window.onload

window.onload = function() {

        what();

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

    }
RIYAJ KHAN
  • 13,830
  • 5
  • 27
  • 48
9

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>
Ronan
  • 79
  • 1
  • 10
user5323957
  • 512
  • 1
  • 7
  • 19
6

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.

RBT
  • 18,275
  • 13
  • 127
  • 181
JT Nolan
  • 1,030
  • 1
  • 9
  • 17
  • 1
    also type attribute in script tags are obsolete. – JT Nolan Aug 14 '13 at 18:31
  • 2
    and importing jquery to solve this is overkill unless you plan to use it for this project here on out. `window.onload` might suffice but there are other events available as well. Ref to MDN on `window`: https://developer.mozilla.org/en-US/docs/Web/API/Window – Sgnl Jun 10 '16 at 00:12
5

<!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>
user6175882
  • 51
  • 1
  • 1
  • Your answer is correct but may I request you to please add some context around your source-code. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT Jan 22 '18 at 21:50
3

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

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

Eddy
  • 31
  • 1
3

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.

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

//or set time out like this:
<script type ="text/javascript">
    setTimeout(function(){
       what();
       function what(){
          document.getElementById('hello').innerHTML = 'hi';
       };
    }, 50);
    //NOTE: 50 is milisecond.
</script>

2) Move js code under HTML code

<div id="hello"></div>
<script type ="text/javascript">
    what();
    function what(){
        document.getElementById('hello').innerHTML = 'hi';
    };
</script>
Pines Tran
  • 61
  • 3
1

<!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>
user2114253
  • 169
  • 1
  • 4
1

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.

1

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.

0

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.

Vishal Kumar Sahu
  • 887
  • 3
  • 13
  • 25
user6175882
  • 51
  • 1
  • 1
0

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

<script>
$( document ).ready(function() {
function what(){
    document.getElementById('hello').innerHTML = 'hi';
};
});
</script>

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

<script type="text/javascript" src="/path/to/main.js" charset="utf-8"></script>

and add the code in main.js file :)

abe312
  • 4,155
  • 30
  • 21
0

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.

Shubham
  • 475
  • 4
  • 7
0

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';  
});
Shrey Tripathi
  • 200
  • 1
  • 7
0

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

Proxybee
  • 94
  • 1
  • 5
  • Please answer as per OPs example. – mishsx Jul 15 '20 at 04:53
  • @mishsx the reason for my reply: I had the exact same error and when I searched I saw everyone's fixes but wasn't the fix in my own case, asking the same question would be duplicating, I felt someone else might be in the exact same situation too and I decided to post my own error and fix as a repl... as you can see it is clearly stated on the reply hence it will be helpful to those in the exact same situation and yet clear to others that this isn't the fix to the error in the question. If this isn't ok, kindly advice on how I should make an alternative error and fix known without duplicating – Proxybee Jul 15 '20 at 08:16
0

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.

HeshanHH
  • 395
  • 3
  • 7
0

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>