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…