dagblog.
← Archive

Internet Explorer, getElementById, and form controls


I’d like to add something to Yuhů’s commendable post At least a little DOM about using 
the standard approach via

Document.getElementByID, which the DOM offers for 
 retrieving part of a document and which consigns the proprietary extension Document.all in Internet Explorer 
to the dustbin.

The problem I’d like to describe can happen when using Internet Explorer’s document.getElementById on
 a document with form controls. It comes down to a clash between the name and id attributes. If the document has
 a form control (an input, for instance) whose name attribute has the same value as the id attribute 
 of any later element, calling document.getElementById returns the form control instead of
 the element with the matching id attribute.

You can verify it all with this simple example.

document.getElementById('foo').style.backgroundColor='red'

.
.
.
Formulářový prvek s atributem name="foo"
Element s atributem id="foo"

Internet Explorer’s behavior is of course incorrect. It can give you some anxious moments
 and make the bug very difficult to track down.

11 March 2004. As Honck pointed out in the discussion below the post, a document with this clash between id and name is written incorrectly as far as HTML is concerned. See Anchors with the id attribute. The validator nonetheless treats a document like this as valid.

Related articles

Medium version

Related articles

Related CZ Podcast episodes