18 Mar

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.

 <div id='testdiv'>test</div>
 <script type='text/javascript'>
  testdiv=document.getElementById('testdiv');
  testdiv.appendChild(document.createTextNode('. all is well'));
 </script>

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 testdiv in the JavaScript above is predefined as the <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.

 <div id='testdiv'>test</div>
 <script type='text/javascript'>
  var testdiv=document.getElementById('testdiv');
  testdiv.appendChild(document.createTextNode('. all is well'));
 </script>

The above should work. Surprising, how simple a workaround can be…

5 thoughts on “getElementById bug in IE6

  1. 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.

  2. 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.

    Cheers

  3. Pingback: Javascript - document.getElementsByTagName | .: TRSplet - internetne storitve .:

Comments are closed.