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:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
	"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<meta name="description" content="A brief description of the content on this page.">
	<title>The name and id attributes in IE</title>
</head>
<body>
	<div id="description">
		<p>A description of something.</p>
	</div>
</body>
</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:

function hideIt() {
	var obj = document.getElementById('description');
	obj.style.display = 'none';
}
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