document.getElementById() may return incorrect element in IE and Opera
By Chris on Aug 29, 2005 | In Scripting, Programming, Bugs, "Features" & Things Not Right | Send feedback »
I came across a bug in Internet Explorer whereby the document.getElementById() function may return an element with a name attribute equal to the id that is specified. This can cause unexpected results.
According to the W3C’s DOM Level 2 Core Specification:
getElementByIdintroduced in DOM Level 2- Returns the
ElementwhoseIDis given byelementId. If no such element exists, returnsnull. Behavior is not defined if more than one element has thisID.Note: The DOM implementation must have information that says which attributes are of type ID. Attributes with the name “ID” are not of type ID unless so defined. Implementations that do not know whether attributes are of type ID or not are expected to return
null.Parameters
elementIdof typeDOMString- The unique
idvalue for an element.Return Value
ElementThe matching element. No Exceptions
http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBId
However, for the browsers that failed the test, it appears that their implimentation of getElementById returns the first element where the ID or name attribute is equal to the specified ID.
This bug was tested against the following browsers:
- IE 6.0 sp2: failed
- IE 5.5: failed
- IE 5.01: failed
- Netscape 7.2: passed
- Netscape 6: passed
- Mozilla 1.7.3: passed
- Opera 8.2: failed
- Firefox 1.0.6: passed
For instance, the following code should produce an alert with “foo=foo; bar=bar”. However, the browsers that fail the test actually return “foo=foo; bar=foo”.
<form name="form1" id="form1" method="get" action="javascript: void(0)">
<input name="bar" type="text" id="foo" value="foo" /><br />
<input name="foo" type="text" id="bar" value="bar" readonly="readonly" /><br />
<input type="button" name="Button" value="Test" onclick="alert(’foo=’+document.getElementById(’foo’).value+’; bar=’+document.getElementById(’bar’).value)" /><br />
</form>
Reported at http://www.quirksmode.org/bugreports/ (permalink)
Noted on http://channel9.msdn.com/wiki/ (Update 2007-04-04: my note has since been replaced by several others
Trackback address for this post
No feedback yet
Leave a comment
| « Amazon.com: Your Profile | CSS Server-side Constants » |