Why are duplicate ID values not allowed in HTML?

It’s always “illegal”. Against the spec = illegal. Just because something “seems to work” due to a fluke or overly generous compiler doesn’t mean it is valid code.

Another way to think about it: juhst becuse u kan reed ths duzint mayke it korrect Englesh. You have a generous compiler/brain which can understand that (e.g Google Chrome), but someone with more limited English knowledge (e.g. new to the market Browser X) or someone with a mental incapacity (e.g. Internet Explorer) might not understand it at all…but would be able to understand it if each word was spelled correctly/according to spec.

https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really

A few reasons I can find:

According to the DOM spec, “If more than one element has an ID attribute with that value, what is returned is undefined”

And:

Incorrect doesn’t come in shades of grey. This code violates the standard and is therefore incorrect. It would fail validation checking, and it should. That said, no browser currently on the market would complain about it, or have any problem with it at all. Browsers would be within their rights to complain about it, but none of the current versions of any of them currently do. Which doesn’t mean future versions might not treat this code badly.

And:

Behavior trying to use that ID as a selector, either in css or javascript, is unguessable and probably varies from browser to browser.

And:

Many javascript libraries will not work as expected

And:

Experience says that getElementById in major browsers will return the first matched element in the document. But this may not always be the case in the future.

Leave a Comment