getElementById gotcha

I was looking, and I can’t stress this enough, at someone else’s HTML/JavaScript. The code looked something like;

<a onMouseOver="elementid.className=’New’" />…<img id="ElementId" src=…>…<div id="elementid">…

so I was asked to find out why this wasn’t working in a number of browsers. Well the first thing I spotted was the non-standard way of accessing the className in OnMouseOver. So I changed it to document.getElementId(‘elementid’).className=’New’; No errors but the style change (which was working in IE with the above code) stopped working in IE. It took a fair bit of head scratching but as you can probably tell by the HTML i’ve added but yet to talk about the problem was the img tag. In the first example of directly setting the className the call is case-sensitive and correctly alters the style of the  DIV. However, and this was a surprise to me, getElementById is case-insensitive and was returning the img tag rather than the DIV! Therefore, and it comes as no real surprise, don’t rely on the case when creating unique Ids.

3 thoughts on “getElementById gotcha

  1. Unknown June 9, 2008 / 7:48 pm

    document.getElementById(id) is _NOT_ case-insensitive… but IE\’s implementation is very broken, and most definately is case-insensitive and also grabs elements from the DOM by name, and has issues with globally scoping any element with an ID or a NAME. (3 separate IE bugs)  See this site for details.id vs. name issue:http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.htmlcase issue:http://webbugtrack.blogspot.com/2007/09/bug-154-getelementbyid-is-not-case.htmlglobal namespace issue:http://webbugtrack.blogspot.com/2007/09/bug-162-global-namespace-pollution-in.htmlBest of luck!

  2. Paulio June 9, 2008 / 11:54 pm

    Yes Microsoft\’s documentations states as much…sIDValue
    Required.
    A String that specifies the ID value. Case-insensitive.I guess maybe it\’s a throw back to VBScript?

  3. Paulio June 10, 2008 / 12:20 am

    Also spotted that it has changed in IE8…sIDValue
    Required.
    A String that specifies the ID. Case-sensitive.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s