Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Jan Baborák
The "Cannot read property 'innerHTML' of null" error occurs for 2 reasons:
innerHTML
property on a null
value - a DOM element that
doesn't exist.Here is an example of how the error occurs.
const box = document.getElementById('does-not-exist'); console.log(box); // 👉️ null // ⛔️ Cannot read properties of null (reading 'innerHTML') const text = box.innerHTML;
To solve the "Cannot read property 'innerHTML' of null" error, make sure
you're using the correct id. The error often occurs when calling the
getElementById
method with an incorrect id
.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- 👇️ `id` should match your JS code --> <div id="box">Box</div> <script src="index.js"></script> </body> </html>
To solve the "Cannot read property 'innerHTML' of null" error, insert the JS script tag at the bottom of the body tag. The JS script should be ran after the DOM elements are created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is ran before div is created ⛔️ --> <script src="index.js"></script> <div id="box">Box</div> </body> </html>
Notice that the index.js
script is ran before the div
element is created.
This means that you can't access the div
inside of the js
file.
const box = document.getElementById('box'); console.log(box); // 👉️ null // ⛔️ Cannot read properties of null (reading 'innerHTML') const text = box.innerHTML;
You should place the JS script tag at the bottom of the body, after the DOM elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Now the index.js
file has access to the div
element.
const box = document.getElementById('box'); console.log(box); // 👉️ div#box // ✅ Works const text = box.innerHTML; console.log(text); // 👉️ "Box"
The "Cannot read property 'innerHTML' of null" error occurs when accessing the
innerHTML
property on a null
value.
To solve the error, make sure the JS script tag is loaded after the DOM elements are declared and you're using an existing identifier to get the element.