getElementById bug in IE6
This one had me scratching my head for a few minutes.
Look at the code below, and tell me what’s wrong with it.
There is nothing wrong with the above, in sane browsers, but IE is not known for its sanity.
Trying the above in IE will result in an “object does not support this method” error.
The reason for this seems to be that IE creates a global variable for each
id that it comes across. In this case, that means that
<div> in the HTML section.
IE’s error message system is hopelessly useless. The error applies to the ‘
=‘ in the line, and not the
getElementById, which is what I was scratching my head about.
So what’s the solution? There are two workarounds:
- use a unique variable name.
- pay attention to scope.
The unique variable name approach is not ideal, as it may make less readable in your code than you’d like, so the solution is to tell the browser that the variable name you’re using applies just to that local scope.
The above should work. Surprising, how simple a workaround can be…
This isn’t a bug. You should define the var as you wouild do in all other languages.
And It’s always been possible to reference an element by it ID directly.
This helped me out a lot, thanks for the post.
Whether or not it is actually a bug, it has caught me out on numerous occasions and I often forget why it is occurring. It doesn’t help that only IE6 behaves this way so it can be a while before anyone notices it.
Yeah thanks for this. Saved me some headaches.