Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by David Beale
The "Cannot set property 'innerHTML' of null" error occurs for 2 reasons:
innerHTML
property on a null value (DOM element that doesn't
exist).Here's an example of how the error occurs.
const el = null; // ⛔️ Cannot set properties of null (setting 'innerHTML') el.innerHTML = 'new value';
To resolve the "Cannot set property 'innerHTML' of null" error, make sure that
the DOM element you're setting the innerHTML
property on exists. The error
most commonly occurs if you use the getElementById()
method and pass it an
id
that is not present in the DOM.
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Cannot set properties of null (setting 'innerHTML') el.innerHTML = 'new value';
In the example, an element with the provided id
does not exist in the DOM, so
the getElementById
method returns a null
value. When we try to set the
innerHTML
property on a null
value, the error gets thrown.
Another common reason for getting the error is placing the JS script tag before declaring the DOM elements.
To solve the "Cannot set property 'innerHTML' of null" error, make sure that the JS script tag is placed at the bottom of the body, after the HTML elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is ran before span exists ⛔️ --> <script src="index.js"></script> <span id="name">John</span> </body> </html>
The JS script tag is added above the code that declared the span
element. The
index.js
file is ran before the span
element is created, therefore we can't
access the span
from the index.js
file.
const el = document.getElementById('name'); console.log(el); // 👉️ null // ⛔️ Cannot set properties of null (setting 'innerHTML') el.innerHTML = 'Alice';
Instead, the JS script tag has to be moved below the DOM elements that it tries to access.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <span id="name">John</span> <!-- ✅ GOOD - span already exists ✅ --> <script src="index.js"></script> </body> </html>
Now, the span
element can be accessed from the index.js
file.
const el = document.getElementById('name'); console.log(el); // 👉️ null // ✅ Works el.innerHTML = 'Alice';
Now that the HTML element is created before the index.js
script is ran, we are
able to access the DOM element and set its innerHTML
property.
The "Cannot set property 'innerHTML' of null" error occurs when:
innerHTML
property on a null
value (a DOM element that
doesn't exist)