PDA

View Full Version : Odd behavior of getElementById?



Keleth
06-23-2008, 05:38 AM
So I'm in an interesting position. I have a small JS code block, at the end of which I set focus on a input with the ID of "username", and name of "username". On the same page, in a different form, I have another input named "username", with no ID.

When I use the "getElementById" function to grab the element with an ID, the code block is returning the input with NO ID. This problem is only occurring on IE (works fine on FF and Opera).

Anyone know what's going on here?

jscheuer1
06-23-2008, 05:43 AM
I'm not sure, but I have heard of similar issues in IE before. Why not give the desired element a unique id (one not used as a name or as anything else) and refer to it that way?

Or you could refer to it as part of the document.forms collection, as long as its name is unique to its form.

Keleth
06-23-2008, 05:52 AM
I guess I was avoiding using the document.forms method :p

Please do correct me if I'm wrong, but I was told that with the evolving DOM, its preferable to get elements by their ID over their names?

jscheuer1
06-23-2008, 07:59 AM
There are so many pages that will be broken if the document.forms collection is dropped, that regardless of what is proclaimed in the standards, it will continue to be supported by browsers at least for certain DOCTYPE declarations, probably for all.

That said, I am unaware of any move to deprecate it, though I do not claim to be up on all of that.

Still, it's your choice, a unique id that isn't also used as a name will also take care of the problem.


I don't know how accurate this:

http://developer.mozilla.org/en/docs/Using_Web_Standards_in_your_Web_Pages:Summary_of_Changes

is, but if it is current, it would seem to indicate that DOM level 1 form methods are even recommended in the standards.

Tabo
06-23-2008, 11:54 AM
Perhaps the NAME of the input is the same as the ID requested. If IE sometimes (because it sucks) returns elements with the name specified in document.getelement... instead of id.

maxgraham
06-23-2008, 10:09 PM
This is a known bug in IE. (with a partial fix in IE8).

The issue is that IE will return the first element it finds, with a match for the ID you supply, on either the name or the id attribute, and worse yet, it doesn't care about the cAsE of your ID.

See these bug reports for more details and workarounds.
http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html

http://webbugtrack.blogspot.com/2007/09/bug-154-getelementbyid-is-not-case.html

Best of luck.