Solve - Cannot read property 'innerHTML' of Null in JS

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

Solve - Cannot read property 'innerHTML' of Null #

The "Cannot read property 'innerHTML' of null" error occurs for 2 reasons:

  1. Accessing the innerHTML property on a null value - a DOM element that doesn't exist.
  2. Placing the JS script tag above the HTML, where the DOM elements are created.
index.js
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.

index.html
<!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.

index.html
<!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 executed before the div element is created. This means that you can't access the div inside of the js file.

index.js
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.

index.html
<!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.

index.js
const box = document.getElementById('box'); console.log(box); // 👉️ div#box // ✅ Works const text = box.innerHTML; console.log(text); // 👉️ "Box"

Conclusion #

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee