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 vs. name issue: issue: namespace issue: of luck!

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

    Yes Microsoft\’s documentations states as much…sIDValue
    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
    A String that specifies the ID. Case-sensitive.

Leave a Reply

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

You are commenting using your 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