JavaScript

Uncaught TypeError: Cannot read property of null

TL;DR;


There are a few variations of this error depending on the property you are trying to access. Sometimes instead of null it will say undefined. An example will be:

Uncaught TypeError: Cannot read property 'value' of null

Uncaught TypeError: Cannot read property 'innerHTML' of null

All this means is that you are trying to access a property of an object that is undefined. These usually happens when we don't test an object before using it. Here is a common scenario.

// We want to get the value of an input. 
var inputVal = document.getElementById("input").value;

This will result in Uncaught TypeError: Cannot read property 'value' of null. The reason will be that the element with id input does not exist. Let me break it down in simpler steps;

var input = document.getElementById("input"); 
input // when this fails, it returns null. input = null
var inputVal = input.value;
// this is the same as the following. 
var inputVal = null.value;
// null does not have the property 'value'

When you break it down, the error actually makes sense. To make sure that you don't get this error, you have to make sure that btn, or any object you use, is not null before you use it. For our example:

var input = document.getElementById("btn");
var inputVal = "";
if (input) {
    inputVal = input.value;
}

Sometimes, your object is nested deeper like Tree.folder.path. You just have to make sure that if you need to access folder, than Tree has to be defined. And if you need to access path, then folder needs to be defined.

In some cases, this error is a symptom of another issue. Why would getElementById return null if the element actually exists on the page? Probably because the function is called before the DOM is ready. Always be careful when accessing a DOM element before it is ready.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only