Site Navigation

Saturday, June 7, 2008

Bug or Feature? - Round Three

Round Three - If more than one ID, which one matches?

Other rounds: [One|Two|Three|Four|Five]

We're back again with another round of "Bug or Feature?" (see round one) highlighting a particular behavior in one or more browsers, that, well, could be a Bug, or it could be a Feature... we'll open up the comments for your vote and opinion.

Alright, what's todays "Bug or Feature"?

Synopsis:
The HTML id attribute is designed to uniquely identify a particular element.

However, what if you accidentally end up with 2 or more elements with the same ID?
Obviously this is a bug, but how different browsers handle it, is what makes it interesting.

All browsers tend to return the first matching element in the DOM order with the same id when using .getElementById(id). However if you have an HTML Label element, with a for attribute that points to the id attribute of a field, things aren't quite so clear.

Firefox, Safari & Opera all link to the first form element with the matching id.
Internet Explorer links to the last form element with the matching id.

Question is, is IE's different behavior a bug? or a feature?

Example HTML snippet:

<label for="obj1_prop1">Size:</label>
<input id="obj1_prop1" type="text" size="5">
<label for="obj1_prop1">Quantity:</label>
<input id="obj1_prop1" type="text" size="5">


Question:
Does linking to the last element vs. the first element expose a feature? or is it a bug?

Test it for yourself, click on the labels Size and Quantity:





Is this a Bug? Or a Feature?

Vote "Bug" or "Feature", and add your thoughts.

4 comments:

Anonymous said...

I would hope to not have duplicate IDs but if I ever did, I would hope to match on the first occurrence, just as getElementById would.

Since there is no good reason to have the last item selected I would say that this is a bug.

Anonymous said...

Bug. I'm with Gerald. The first match is the correct match.

Anonymous said...

it might be a feature if you think of the scenario where you insert multiple fields. e.g. like if you say "add a row" for a form then the label will jump to the last row instead of the first.

Unknown said...

In my opinion it's not a bug nor a feature. Why? The DOM spec doesn't say clearly how to handle duplicate ID's, because ID's are mentioned to be unique (the spec says: Behavior is not defined if more than one element has this ID). I assume all browsers search for element with ID given and return the first occurrence. IE - as we all know - caches all elements in document.all, so every duplicate ID will overwrite the old entry, and maybe IE uses the document.all internally to find the elements.