Cannot set property 'innerHTML' of null
Solution 1:
You have to place the hello
div before the script, so that it exists when the script is loaded.
Solution 2:
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:
-
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 wherebody
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>
-
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 withhello
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 thehead
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>
Solution 3:
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>