Page 1 of 1

Uncaught TypeError: Cannot set property innerHTML of null

Posted: 07 May 2015, 08:36
by PloMar
I have this JS script:

Code: Select all

<script>
function blockToggle(type,blockee,elem){
	var conf = confirm("Press OK to confirm the '"+type+"' action");
	if(conf != true) return false;
	var elem = document.getElementById(elem);
	elem.innerHTML = 'please wait ...';
}
</script>
In console it shows this error:

Code: Select all

Uncaught TypeError: Cannot set property 'innerHTML' of null
What is the cause and how to fix it?

Uncaught TypeError: Cannot set property innerHTML of null

Posted: 07 May 2015, 08:40
by MarPlo
The error message indicates that there is not a HTML element in page with the id passed in the "elem" arguments.
Check the part of your JavaScript code where that function is accessed to see what id is passed to the "elem" parameter, then make sure you have a HTML element with that id in webpage.

Uncaught TypeError: Cannot set property innerHTML of null

Posted: 27 Apr 2020, 06:12
by warrenfelsh
In JavaScript almost everything is an object, null and undefined are exception. When you try to access an undefined variable it always returns undefined and we cannot get or set any property of undefined. In that case, an application will throw Uncaught TypeError.

In most cases, you are missing the initialization . So, you need to initialize the variable first. Moreover, if you are not sure a variable that will always have some value, the best practice is to check the value of variables for null or undefined before using them. If you just want to check whether there's any value, you can do:

Code: Select all

if( value ) {
  //do something
}
Or, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator .

Code: Select all

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {
  //deal with value
}