getElementById fails on IE

While working on a simple test page, I wanted to use getElementById to get an Image object from JavaScript.  I quickly wrote up the code and tried it.  Firefox was fine but it failed on my IE7 with “Microsoft JScript runtime error: Object doesn’t support this property or method”.  It took some digging to see what the problem was.

First thing I checked was that I used both element Name and Id and that they were the same.  I *always* do that given that IE will use whichever one matches the desired string.  After reading a few blog posts about common problems but with no good ideas I went back to my code and reviewed it carefully.  It turns out that I used the same name for my element and my local JavaScript variable.  That by itself isn’t a problem but what made it an issue for me was that I failed to initialize my variable with the “var” keyword.

See the code below for the example:

Do Something