Cannot set property ‘innerHTML’ of null or “Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)” is a very common error when you call JavaScript from the HTML. In this article, you will know the different possible reasons for this error and their possible solutions.
What is meant by “cannot set property ‘innerHTML’ of null”?
InnerHTML sets or returns the HTML content of the HTML element. It will be executed only on the HTML element.
If the getElementById(“”) does not find the required element for the input id, then it returns a null value and when innerHTML is executed on the null value it throws “cannot set property ‘innerHTML’ of null” error message.
The followings are the possible three scenarios where you may get the “cannot set property ‘innerHTML’ of null” error message.
1. HTML DOM element is not loaded before the JavaScript
All the web browsers load the HTML elements and JavaScript codes written inside the Script tag from top to bottom. If you are trying to access the HTML node element from the script tag, you must make sure that it is already loaded by the browser before executing the script code or it may result in “Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)” error.
Example:
In the following example, content of the HTML element
is called inside the script tag before it is actually loaded by the browser. This is because firstElement
is declared after the script tag. The browser first executes the script tag and then the firstElement
div tag sequentially which results in an error message.firstElement
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Tech Support Whale Document</title> <script type ="text/javascript"> testScript(); function testScript(){ document.getElementById('firstElement').innerHTML; }; </script> </head> <body> <div id="firstElement">Welcome to TechSupportWhale !</div> </body> </html>
Solution:
Declare the id
above the script tag. So that browser loads the firstElement
before calling the script tag as shown below. The browser executes the javascript code without any error message.firstElement
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Tech Support Whale Document</title> <body> <div id="firstElement">Welcome to TechSupportWhale !</div> </body> <script type ="text/javascript"> testScript(); function testScript(){ document.getElementById('firstElement').innerHTML; }; </script> </head> </html>
2. Incorrect DOM element ID
There is a possibility you might have mistyped element id passed to the getElementById(“”) function. Double-check if you have the correct element id passed.
<body> <div id="firstElement">Welcome to TechSupportWhale !</div> </body> <script type ="text/javascript"> testScript(); function testScript(){ document.getElementById('firstElemen').innerHTML; }; </script>
In the above example, the wrong element id is passed to the getElementById function. GetElementById(“”) function fails to read the input element id that causes the error.
3. Access DOM Element using windows.load event
Alternately you can also use windows.onload
event which executes when bowser is finished loading all the other DOM elements. So your javascript code will not fail even if you call it before the declaration of the element node as shown below.
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Tech Support Whale Document</title> <script type ="text/javascript"> window.onload = function() { testScript(); function testScript(){ document.getElementById('firstElement').innerHTML; }; } </script> <body> <div id="firstElement">Welcome to TechSupportWhale !</div> </body> </head> </html>
In the above example windows.onload
function holds execution of testScript()
until browser loads the firstElement
element node.
Conclusion:
These are the three different solutions to solve “cannot set the property ‘innerHTML’ of null” and I hope the error is resolved now. If you are still facing the issue, do share your HTML code in the comment section or you can reach out to us using the Contact Form, we will try to resolve your query to the best of our knowledge.
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
15.4k3 gold badges28 silver badges41 bronze badges
asked Aug 14, 2013 at 18:25
You have to place the hello
div before the script, so that it exists when the script is loaded.
RBT
23.6k21 gold badges158 silver badges239 bronze badges
answered Aug 14, 2013 at 18:31
Erik GodardErik Godard
5,8406 gold badges29 silver badges33 bronze badges
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 with idhello
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>
answered Apr 11, 2017 at 8:59
RBTRBT
23.6k21 gold badges158 silver badges239 bronze badges
2
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>
answered Aug 14, 2013 at 18:33
Colyn1337Colyn1337
1,6652 gold badges18 silver badges27 bronze badges
1
Just put your JS in window.onload
window.onload = function() {
what();
function what() {
document.getElementById('hello').innerHTML = 'hi';
};
}
answered Feb 1, 2016 at 6:09
RIYAJ KHANRIYAJ KHAN
15k5 gold badges31 silver badges53 bronze badges
1
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>
Jij
1051 gold badge2 silver badges12 bronze badges
answered Feb 1, 2016 at 5:59
user5323957user5323957
5421 gold badge8 silver badges21 bronze badges
1
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
23.6k21 gold badges158 silver badges239 bronze badges
answered Aug 14, 2013 at 18:30
JT NolanJT Nolan
1,1801 gold badge9 silver badges17 bronze badges
2
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>
answered May 23, 2015 at 5:28
<!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>
answered Apr 8, 2016 at 7:14
1
You could try using the setTimeout method to make sure your html loads first.
answered Aug 22, 2016 at 17:27
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>
answered Mar 2, 2019 at 6:48
Pines TranPines Tran
5413 silver badges6 bronze badges
<!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>
answered Jul 23, 2017 at 7:31
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.
answered Aug 20, 2017 at 21:02
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.
answered Jan 23, 2019 at 21:33
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 🙂
answered Oct 9, 2016 at 21:08
abe312abe312
2,53724 silver badges16 bronze badges
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.
answered Apr 8, 2016 at 7:12
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.
answered Oct 18, 2019 at 5:45
ShubhamShubham
6679 silver badges7 bronze badges
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';
});
answered May 28, 2020 at 10:57
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
answered Jul 15, 2020 at 4:24
ElizabethElizabeth
1762 silver badges10 bronze badges
2
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.
answered Aug 4, 2020 at 19:41
HeshanHHHeshanHH
6436 silver badges9 bronze badges
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>
answered Apr 20, 2021 at 12:00
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 %}
answered Aug 27, 2021 at 3:06
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
15.4k3 gold badges28 silver badges41 bronze badges
asked Aug 14, 2013 at 18:25
You have to place the hello
div before the script, so that it exists when the script is loaded.
RBT
23.6k21 gold badges158 silver badges239 bronze badges
answered Aug 14, 2013 at 18:31
Erik GodardErik Godard
5,8406 gold badges29 silver badges33 bronze badges
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 with idhello
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>
answered Apr 11, 2017 at 8:59
RBTRBT
23.6k21 gold badges158 silver badges239 bronze badges
2
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>
answered Aug 14, 2013 at 18:33
Colyn1337Colyn1337
1,6652 gold badges18 silver badges27 bronze badges
1
Just put your JS in window.onload
window.onload = function() {
what();
function what() {
document.getElementById('hello').innerHTML = 'hi';
};
}
answered Feb 1, 2016 at 6:09
RIYAJ KHANRIYAJ KHAN
15k5 gold badges31 silver badges53 bronze badges
1
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>
Jij
1051 gold badge2 silver badges12 bronze badges
answered Feb 1, 2016 at 5:59
user5323957user5323957
5421 gold badge8 silver badges21 bronze badges
1
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
23.6k21 gold badges158 silver badges239 bronze badges
answered Aug 14, 2013 at 18:30
JT NolanJT Nolan
1,1801 gold badge9 silver badges17 bronze badges
2
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>
answered May 23, 2015 at 5:28
<!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>
answered Apr 8, 2016 at 7:14
1
You could try using the setTimeout method to make sure your html loads first.
answered Aug 22, 2016 at 17:27
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>
answered Mar 2, 2019 at 6:48
Pines TranPines Tran
5413 silver badges6 bronze badges
<!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>
answered Jul 23, 2017 at 7:31
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.
answered Aug 20, 2017 at 21:02
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.
answered Jan 23, 2019 at 21:33
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 🙂
answered Oct 9, 2016 at 21:08
abe312abe312
2,53724 silver badges16 bronze badges
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.
answered Apr 8, 2016 at 7:12
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.
answered Oct 18, 2019 at 5:45
ShubhamShubham
6679 silver badges7 bronze badges
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';
});
answered May 28, 2020 at 10:57
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
answered Jul 15, 2020 at 4:24
ElizabethElizabeth
1762 silver badges10 bronze badges
2
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.
answered Aug 4, 2020 at 19:41
HeshanHHHeshanHH
6436 silver badges9 bronze badges
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>
answered Apr 20, 2021 at 12:00
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 %}
answered Aug 27, 2021 at 3:06
The innerHTML property lets you set the contents of an element using JavaScript.
If you specify an invalid element with which to use the innerHTML method, or if you place your script before the element appears on the page, you’ll encounter the “Uncaught TypeError: cannot set property ‘innerHTML’ of null” error.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
In this guide, we discuss what this error means and why you may encounter it. We’ll walk through an example of this error so you can learn how to resolve it in your JavaScript code.
Uncaught TypeError: cannot set property ‘innerHTML’ of null
The innerHTML property is associated with any web element that you are working with in JavaScript. You may have selected a web element from the page using a “getter” like getElementById(), or you may have created an element in JavaScript that you want to modify.
The “cannot set property ‘innerHTML’ of null” error is a type error. This means we are trying to apply a property or a function to a value that does not support a property or function.
In this case, we’re trying to set the value of innerHTML on an element that is equal to null. Null values do not have an innerHTML property.
There are two common causes of this error:
- Placing a script before an element appears on the web page
- Referencing the wrong element ID.
We’re going to walk through the first cause, which is arguably the most common mistake made by beginners.
An Example Scenario
We’re going to write a simple website that displays the time. To start, define a basic HTML page. This HTML page will be the canvas on which we display the time:
<!DOCTYPE html> <html lang="en"> <head> <title>Time</title> </head> <body> <p>The time is <span id="show_time"></span>.</p> </body> </html>
This HTML page contains a <head>
and a <body>
tag. The <head>
tag contains a <title>
tag which defines the title for the web page. The <body>
tag contains a paragraph.
Within the paragraph, we have added a <span> tag. We’re going to replace the contents of this tag with the current time in our JavaScript code.
Next, write a script to retrieve the time. We’ll add this JS code inside the <head>
tag:
… <title>Time</title> <script> var show_time = document.getElementById("show_time"); var current_date = new Date(); var pretty_time = `${current_date.getHours()}:${current_date.getMinutes()}` show_time.innerHTML = pretty_time; </script> …
Our document now contains HTML and JavaScript. The getElementById()
method retrieves our show_time
span tag. We then retrieve the current date using the JavaScript Date module.
On the next line of code, we create a string which displays the current hour of the day and the minute of the hour. This string uses the following structure:
HH:MM
There is a colon that separates the hour and minute values. We create this string using a technique called JavaScript string interpolation. This lets us embed multiple values into the same string. Finally, we use the innerHTML method to display this time on our web page.
Let’s open up our web page in the web browser:
Our web page fails to display the time. If we look at the JavaScript console, we can see an error:
Uncaught TypeError: show_time is null
This is another representation of the “cannot set property ‘innerhtml’ of null”. It tells us the element on which we are trying to set the value of innerHTML is null.
The Solution
Because the value of show_time
is null, we can infer that JavaScript was unable to successfully retrieve the element whose ID is show_time
.
In this case, the cause is that we have placed our <script>
tag too early in our program. Our <script>
tag appears in the header of our page. This is a problem because without using an onload()
function, we can only select elements that come before our <script>
.
To solve this error, we need to move our <script>
below our paragraph:
... <body> <p>The time is <span id="show_time"></span>.</p> </body> <script> var show_time = document.getElementById("show_time"); var current_date = new Date(); var pretty_time = `${current_date.getHours()}:${current_date.getMinutes()}` show_time.innerHTML = pretty_time; </script> …
We have moved our <script>
tag below the <body>
tag. Let’s try to open our web page again:
The web page successfully displays the time.
If this does not solve the error for you, make sure that you correctly select the element that you want to work with in your code. For instance, consider this line of code:
var show_time = document.getElementById("show_times");
If we used this line of code to select our element, we would see the same error that we encountered before. This is because there is no element whose ID is “show_times”.
Conclusion
The “Uncaught TypeError: cannot set property ‘innerHTML’ of null” error is caused by trying to set an innerHTML value for an element whose value is equal to null.
“Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!”
Venus, Software Engineer at Rockbot
To solve this error, make sure your <script>
tag comes after the element that you want to select in your script. If this does not solve the issue, check to make sure you are selecting a valid element in your program.
pbarovsky 0 / 0 / 0 Регистрация: 02.04.2022 Сообщений: 6 |
||||||||
1 |
||||||||
02.04.2022, 23:45. Показов 3774. Ответов 2 Метки css, html, innerhtml, java script, jquerry, js, node, socket.io (Все метки)
Сам недавно начал заниматься js. Решил написать чат на сокете и экспресс по видео. Писал всё ровно по видео. Помогите исправить ошибку. Перестановка объявления скрипта в html не помогает. ошибку выдаёт строчка кода: JS код (main.js):
HTML код:
0 |
Модератор 2302 / 1528 / 678 Регистрация: 13.03.2010 Сообщений: 5,179 |
|
02.04.2022, 23:50 |
2 |
Сообщение было отмечено pbarovsky как решение РешениеТочки нет в названии класса.
1 |
0 / 0 / 0 Регистрация: 02.04.2022 Сообщений: 6 |
|
03.04.2022, 15:44 [ТС] |
3 |
СПАСИБО БОЛЬШОЕ!!!
0 |