Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Web

Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

· 9 min read

You want to show a greeting on your page. The JavaScript is one line, but nothing appears, and the browser console says:

Console
Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

Cannot set properties of null (setting 'innerHTML') means JavaScript tried to put content into an element, but instead of an element it had null: nothing. The element wasn't found. Almost always, one of four things happened: the script ran before the HTML element existed, the id is misspelled, the selector is missing a # or ., or the element is on a different page. This article shows how to tell which one it is, with the fix for each.

Try it yourself

Save this as index.html and open it in your browser, then open the console (F12, or right-click and choose Inspect, then the Console tab):

index.html
<!doctype html>
<html>
<head>
  <script>
    document.getElementById("greeting").innerHTML = "Hello, Sam";
  </script>
</head>
<body>
  <p id="greeting"></p>
</body>
</html>

You'll see the error above in Chrome or Edge. The paragraph exists, the id is right, and still the script can't find it. Cause 1 explains why.

What the error means

Read the message from the end:

  • (setting 'innerHTML'): your code tried to set the innerHTML property, to change the content of something.
  • of null: that something was null, JavaScript's value for "nothing here".
  • Cannot set properties: you can't set anything on nothing.

So the real question isn't about innerHTML at all. It's: why did document.getElementById("greeting") give back null?

getElementById and querySelector return the element if they find it, and null if they don't. They don't raise an error themselves. The error appears one step later, when you try to use the result.

Cause 1: the script runs before the element exists

The browser reads an HTML page from top to bottom and runs each <script> as soon as it reaches it. In the example, the script is in the <head>, so it runs before the browser has even read the <body>. At that moment, there is no element with the id greeting yet.

There are three ways to fix it, and all of them work.

Fix 1: move the script to the end of the body

html
<body>
  <p id="greeting"></p>
  <script>
    document.getElementById("greeting").innerHTML = "Hello, Sam";
  </script>
</body>

Now the paragraph exists by the time the script runs.

Fix 2: use defer with an external file

If your JavaScript is in its own file, keep the <script> tag in the <head> and add defer:

html
<head>
  <script defer src="app.js"></script>
</head>

defer tells the browser to download the file right away but run it only after the whole page has been read. In our test, the same line in app.js with defer set the greeting without an error. This is the most common setup in modern pages. (defer only works on scripts with a src, not on inline scripts.)

Fix 3: wait for DOMContentLoaded

If the script must stay inline in the <head>, wrap the code in an event that fires when the page has been read:

js
document.addEventListener("DOMContentLoaded", () => {
  document.getElementById("greeting").innerHTML = "Hello, Sam";
});

Cause 2: a typo in the id

The script runs at the right time, but the id doesn't match:

html
<p id="greeting"></p>
<script>
  document.getElementById("greting").innerHTML = "Hello";
</script>
Console
Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

greting is missing an e. Ids must match exactly, including capital letters: Greeting and greeting are different ids. Copy the id from the HTML into the JavaScript rather than typing it twice.

Cause 3: a selector without # or .

querySelector uses CSS selectors, so an id needs a # and a class needs a .:

html
<p class="total"></p>
<script>
  document.querySelector("total").textContent = "42";
</script>
Console
Uncaught TypeError: Cannot set properties of null (setting 'textContent')

querySelector("total") looks for an HTML tag called <total>, which doesn't exist. Write querySelector(".total") for a class, or querySelector("#total") for an id.

The opposite mistake is as common: getElementById("#greeting") with a #. getElementById takes the plain id, without #, so it searches for an id that literally starts with #, and finds nothing.

Cause 4: the element is on another page

If one JavaScript file is shared by several pages, code for an element on index.html will also run on about.html, where that element doesn't exist. On that page, the result is null, and the error appears.

The fix is to check before you use the element:

js
const greeting = document.getElementById("greeting");
if (greeting) {
  greeting.innerHTML = "Hello, Sam";
}

Or, in short, with optional chaining for reading: greeting?.textContent. (Optional chaining can't be used on the left side of =, so for setting a value, the if is the way.)

The same error with other properties

The property name at the end changes with what you tried to set. In our tests with Chromium, these all came from the same cause, a null element:

Console
Cannot set properties of null (setting 'innerHTML')
Cannot set properties of null (setting 'textContent')
Cannot set properties of null (setting 'value')
Cannot set properties of null (setting 'onclick')
Cannot set properties of null (setting 'src')
Cannot set properties of null (setting 'disabled')

Notice the word set. When you read a property, or call a method, the message says read instead:

Console
Uncaught TypeError: Cannot read properties of null (reading 'style')
Uncaught TypeError: Cannot read properties of null (reading 'classList')

element.style.color = "red" first reads style from the element, which is why it gives the "reading" version. For the most common one, see Cannot read properties of null (reading 'addEventListener'): same cause, same fixes.

The older wording

Older versions of Chrome said this differently:

Console
Uncaught TypeError: Cannot set property 'innerHTML' of null

Many forum answers still use this wording. It's the same error.

In Firefox and Safari

Other browsers describe it in their own words. Firefox usually names the expression that was null, for example document.getElementById(...) is null. Whatever the wording, look for the element lookup on that line.

The undefined version: getElementsByClassName

getElementsByClassName returns a list of elements, never null. Setting innerHTML on the list does nothing at all, without any error:

js
document.getElementsByClassName("msg").innerHTML = "Hi";

That silent version is a bug, not an error, and it's confusing because nothing happens. You have to choose an element from the list: document.getElementsByClassName("msg")[0], or better, document.querySelector(".msg"), which returns the first match directly.

And if the list is empty, [0] gives undefined, and the message changes:

Console
Uncaught TypeError: Cannot set properties of undefined (setting 'innerHTML')

Undefined here means "the list had no first element": the class name didn't match anything.

Errors that look alike

  • Cannot read properties of null (reading 'addEventListener'): the same missing element, used with a method instead of a property. See the addEventListener article.
  • Cannot set properties of undefined: usually an empty list from getElementsByClassName(...)[0], or a property of an object that doesn't exist.
  • x is not defined: the variable itself doesn't exist, which is different from a variable that holds null.
  • Styles not changing, with no error: see CSS not working.

Wrong fixes that don't help

  • Wrapping everything in try/catch. The error disappears, and so does your greeting. The element is still not found.
  • Adding setTimeout to wait. It sometimes works by luck. defer or moving the script is reliable.
  • Using document.write. It's outdated, and it can replace the whole page.

A debugging walkthrough

Your page shows nothing and the console has Cannot set properties of null (setting 'innerHTML'):

  1. Click the link at the right of the error in the console. It opens the exact line.
  2. Find the lookup on that line or just above: getElementById(...) or querySelector(...).
  3. Type the lookup into the console and press Enter, for example document.getElementById("greeting"). If it prints null now, the id or selector is wrong. If it prints the element now, your script ran too early.
  4. Too early? Add defer, or move the script to the end of <body>.
  5. Wrong id? Compare the HTML and the JavaScript, letter by letter, and check for # and ..

Step 3 is the quickest test: it tells you in one line which of the two big causes you have.

Practice

Which of these give the error, if the page has <p id="score"></p> and the script is at the end of the body?

  1. document.getElementById("score").innerHTML = "10";
  2. document.querySelector("score").innerHTML = "10";
  3. document.getElementById("#score").textContent = "10";

Answers. (1) Works. (2) Error: without #, querySelector looks for a <score> tag. (3) Error, (setting 'textContent'): getElementById doesn't take a #.

Frequently asked questions

What does "Cannot set properties of null" mean?

You tried to set a property, like innerHTML, on null. The element lookup before it didn't find anything.

Why is getElementById returning null?

Either the script runs before the element exists, or the id doesn't match exactly. Test it in the console to see which.

Should I use innerHTML or textContent?

For plain text, use textContent: it's safer, because it never treats the text as HTML. Use innerHTML only when you really want to insert HTML tags.

Where should I put the script tag?

Either at the end of <body>, or in <head> with defer and a src file. Both make sure the HTML exists before your code runs.

Is this the same as "Cannot set property 'innerHTML' of null"?

Yes. That's the older Chrome wording of the same error.

A quick checklist

  1. Run the lookup in the console: null or an element?
  2. Element in the console but null in the script? The script runs too early: use defer.
  3. null in the console? Check the id letter by letter, and # or . in the selector.
  4. Shared script? Check that the element exists before using it.
  5. Prefer textContent for plain text.

For a method that works on any error, read how to read an error message. MDN explains getElementById and the defer attribute.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Java

Java error: cannot find symbol, and how to fix it

Fix Java's error: cannot find symbol: read the symbol and location lines, then fix typos, missing imports, variables out of scope and wrong method names. With compiled examples.

Error explained · · 10 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right