Beware of id and name attribute mixups when using getElementById in Internet Explorer

It is probably old news to the JavaScript experts among you, but since I recently ran into this problem myself and pulled my hair in frustration before a coworker hinted at the solution I think it's worth mentioning:

When using getElementById to get a reference to an element via the id attribute, Internet Explorer for Windows (and some versions of Opera) will also match an element whose name attribute contains the same value.

This doesn't always cause any noticeable problems since in most cases you're not all that likely to have identical name and id values for different elements, but when it does happen it can lead to errors that are very hard to debug.

Here is a simple example HTML document that is susceptible to this problem:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  2. "http://www.w3.org/TR/html4/strict.dtd">
  3. <html>
  4. <head>
  5. <meta name="description" content="A brief description of the content on this page.">
  6. <title>The name and id attributes in IE</title>
  7. </head>
  8. <body>
  9. <div id="description">
  10. <p>A description of something.</p>
  11. </div>
  12. </body>
  13. </html>

Now imagine that you want to use JavaScript to do something to div#description. For simplicity's sake, let's say you write the following script that hides the div element by setting its display CSS property to none when the page is loaded:

  1. function hideIt() {
  2. var obj = document.getElementById('description');
  3. obj.style.display = 'none';
  4. }
  5. window.onload = hideIt;

That works as expected everywhere except in Internet Explorer, where nothing happens. The reason for that is that in IE, getElementById finds and returns the meta element whose name attribute has the value description before it gets to the div element.

You can avoid this either by making sure that there are no name and id conflicts in your document or by using a script that fixes the problem by overriding IE's native getElementById method.

If you were aware of this already, good for you. If not, I hope I saved you some frustration.

Posted on February 14, 2008 in JavaScript, Browsers