Skip to content Skip to sidebar Skip to footer

Status.style Is Undefined

The browser’s console says: TypeError: status.style is undefined, line 12 var status; function output(msg,type='info'){ status.innerHTML=msg; switch(type){ cas

Solution 1:

You’re not actually referring to your status variable, but to window.status.

There are two possible solutions to this:

  • Simply don’t use status, but another variable name instead, or
  • Wrap your code in an IIFE like this: (function(){…}());

window.status is a special property: it has a WebIDL binding. In this case, this basically means that the value of the property is changed and updated secretly. In the case of window.status, whenever a value is assigned to it, it is turned into a string. That’s why console.log(status) yields the string

"[object HTMLDivElement]"

instead of the element

<div id="status">

And only HTML elements have the style property, not strings. That’s why status.style is undefined.

That’s not an issue if you access an undefined property of a defined value. That’s why status.innerHTML didn’t throw the error. But with status.style.background, you tried to access an undefined property of an undefined value.

If you use immediately invokable function expressions (IIFEs), you can use whichever variable names you want:

(function(){
  var status;
  // etc.
})();

window.status was used to set the status text of a window (back then, when browsers had status bars).


Post a Comment for "Status.style Is Undefined"