Uncaught TypeError: Cannot set property innerHTML of null

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

Uncaught TypeError: Cannot set property innerHTML of null

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?

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.

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
}

Similar Topics