1

I have a null check in my javascript code that doesn't seem to operating as expected. It goes like this:

if (myVariable) {
// Do things with my variable
}

When I reach the inside of the if statement, Chrome's java console says the value I'm trying to use (myVariable) is null. Perhaps I'm not understanding the if statement properly? The specific line throwing the error is

window.document.getElementById("myElement").innerText = myVariable

Thanks in advance.

2 Answers2

8

It's telling you that

window.document.getElementById("myElement")

is null. That probably means that your code is running before the DOM has been parsed.

Exactly how you should fix it depends on code you haven't shown us, but as an experiment you could try moving that code to a <script> tag at the end of the <body> and see if that helps. Also, verify that "myElement" really is the "id" of the element you intend to target.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • So it seems even though myElement existed, because it was an ASP Label it was not being found by Javascript? I changed it to a text box and it works fine. I'll select this as the answer because you suggested looking for if myElement existed. – Garrett Daniel DeMeyer Jun 19 '13 at 17:58
  • 1
    Ah, well in ASP the actual "id" value that gets to the browser is not the same as the value you code into the .asp file. If you do a "view source" or use the browser DOM inspector you can see what the actual "id" value is. There's a way to get that from ASP but I'm not sure what it is; there are zillions of Stackoverflow questions that have that detail however :-) – Pointy Jun 19 '13 at 18:07
0

When you assign something to a null or undefined value, that's not a problem and exception should not be thrown.

for example you can explicitly say:

var something = null;
var somethingElse = undefined;
var somethingOtherThing = myNonExistentObject;

This seems to mean that you misinterpretted the exception? Or something else is wrong. Such as the thing whose property you are trying to assign, is null or undefined.

The following will raise an error:

var something = null;
something.foo = 123; //error! something is null.
Lzh
  • 3,585
  • 1
  • 22
  • 36