By Joshua W


2013-08-14 18:25:51 8 Comments

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>

19 comments

@HeshanHH 2020-08-04 19:41:58

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.

@Proxybee 2020-07-15 04:24:31

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

@mishsx 2020-07-15 04:53:38

Please answer as per OPs example.

@Proxybee 2020-07-15 08:16:37

@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

@Shrey Tripathi 2020-05-28 10:57:22

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';  
});

@RBT 2017-04-11 08:59:17

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>

@barlop 2019-07-26 14:30:27

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.jsfiddle.net/fbz6wLpd/8

@Shubham 2019-10-18 05:45:34

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.

@Colyn1337 2013-08-14 18:33:50

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>

@Erik Godard 2013-08-14 18:31:30

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

@Colyn1337 2013-08-15 14:05:31

If you use window.onload = function name(){} it doesn't matter if the div is before or after.

@Sahu V Kumar 2017-04-09 17:29:53

Crispy solution. But I am getting the error still. In chrome/fedora 25/apache

@Pines Tran 2019-03-02 06:48:04

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>

@Marko Slijepčević 2019-01-23 21:33:45

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.

@JT Nolan 2013-08-14 18:30:29

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.

@JT Nolan 2013-08-14 18:31:21

also type attribute in script tags are obsolete.

@Sgnl 2016-06-10 00:12:47

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: developer.mozilla.org/en-US/docs/Web/API/Window

@plagueanomicPlague 2017-08-20 21:02:32

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.

@user2114253 2017-07-23 07:31:13

<!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 2017-07-23 07:33:12

problem is fist html div loaded ..than java script function calling now it work...

@user6175882 2016-04-08 07:12:36

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.

@abe312 2016-10-09 21:08:58

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

@Eddy 2016-08-22 17:27:44

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

@user6175882 2016-04-08 07:14:44

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

@RBT 2018-01-22 21:50:06

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.

@RIYAJ KHAN 2016-02-01 06:09:36

Just put your JS in window.onload

window.onload = function() {

        what();

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

    }

@user5323957 2016-02-01 05:59:24

The JavaScript Part Need To Run Once Page Is Loaded Therefor It Is Advised To Place JavaScript Script At The End Of 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>

@VortexYT 2018-07-10 15:34:54

Will You Please Stop Capitalising Every Word You Type?

@user4909217 2015-05-23 05:28:21

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>

Related Questions

Sponsored Content

29 Answered Questions

[SOLVED] Iterate through object properties

43 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

63 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

31 Answered Questions

[SOLVED] How can I determine if a variable is 'undefined' or 'null'?

46 Answered Questions

[SOLVED] Detecting an undefined object property

13 Answered Questions

[SOLVED] How to replace innerHTML of a div using jQuery?

47 Answered Questions

[SOLVED] Sort array of objects by string property value

46 Answered Questions

[SOLVED] How can I check for an empty/undefined/null string in JavaScript?

41 Answered Questions

41 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery

Sponsored Content