Monday, September 25, 2006

Document.getElementById Bug/Problem

The getElementById method is supposed to return the first element in the document with the specified id. See the spec. There is a bug in IE (perhaps it's intentional), that will return an element with the name, instead of the id.

Try out the following. Get element by ID and display it's ID. You'd think it would be the same id that was just asked for, in this case 'child'...

< type="checkbox" onclick="alert('child = ' + document.getElementById('child').id)">
< type="hidden" name="child" id="hidden_child">
< type="checkbox" id="child">

To work around this - make sure you keep id's unique to each other and to elements that are named. Or be sure the id elements are found first, in document order.

1 comment:

  1. Anonymous11:53 AM

    Keeping the IDs and NAMEs unique is fine, but on any complex site, can be a nightmare.

    There is a nice fix for the bug in IE's getElementById( id ) method on this site:

    It shows you how you can fix IE's version of the method to always return the correct element.