8

Under what circumstances is it illegal for an HTML page to contain elements with duplicate ID attributes?

As a developer who has worked with HTML for many years, I am aware that the intention is that element ids should be unique - what I am asking is for the practical negative effects of duplicate ids.

Granted, getElementByID()-like functions in some libraries might return arrays rather than a single element and this could cause issues when the developer had not anticipated this case. However, as far as I know, such functions will continue to operate so clearly they are not a breaking-effect of id duplicates.

So why is it that duplicate ids are said to be not allowed?

EDIT: The driver for the question was that I saw some templating libraries when generating list/repeated items, producing elements with duplicate ids and I wondered what the impact of that might be in practical terms and how to decide whether to adopt those libraries.

I also wondered about the effect of modal plugins, or any other, that might clone an existing hidden node and thereby create a duplicate via code, and then what the browser would do in that case.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
  • 3
    `getElementById` only returns one element and never an array. Same with a jQuery ID selector...will not look for more than one, will not return more than one – charlietfl Jan 13 '18 at 13:23
  • 2
    @Luca and OP, if you are writing JS, consider using data-* attributes instead of classes. This allows you to completely separate JS/CSS concerns. There are some small performance benefits to worry about, but the benefits to our code maintainability have increased more than the supposed millisecond level slowdowns. – KayakinKoder Jan 13 '18 at 13:29
  • 1
    Generally speaking, browsers, whatever they are doing, do not crash in the face of invalid markup. So you will always get some behaviour, and the HTML spec is written such that the behaviour is defined, and consistent across browser implementations. In most cases other than CSS selectors, the match will be on the first element in the DOM with the given ID. So mostly, failure modes will be that the match will not be on the element that you intended it to match. – Alohci Jan 13 '18 at 14:35
  • 1
    Regarding your edit: I would not consider using a template library that does create invalid HTML. – str Jan 13 '18 at 16:22
  • 1
    Ids must be unique because that's what the word "identity" **means**! The whole reason for being of an ID is to uniquely _identify_ an element. To say to the world, "this is the one we're talking about". If you don't want that, then simply don't use IDs. – Mr Lister Jan 13 '18 at 21:28
  • @MrLister - sure but I was asking about the practical impact, not the theoretical. If you think about it, browsers don't balk at a document containing duplicated ids. So - are the browsers wrong or is the spec wrong, or did the browser coders see something impractical in the spec? – Vanquished Wombat Jan 13 '18 at 23:02
  • @str - your opinion is valued but could you back it up with some discourse on the facts that lead you to it? – Vanquished Wombat Jan 13 '18 at 23:04
  • @VanquishedWombat Answers were already given, so my comment only addressed one point that the answers hadn't mentioned yet. Also, it depends on your definition of "balk". For example, css `#one:target {...}` with multiple IDs `"one"`. Some browsers will assign the styles only to the first element with the ID, others to all of them. Things like that. – Mr Lister Jan 14 '18 at 08:27
  • @VanquishedWombat See my answer on your question. And as for template libraries: Those are supposed to create HTML. But invalid HTML is not HTML, just HTML-like. So I think it is pretty obvious that you should not use such a library. – str Jan 14 '18 at 09:15
  • 1
    @MrLister - thanks - can you name a browser that would behave in the way you describe with your #one example? – Vanquished Wombat Jan 14 '18 at 19:11
  • @VanquishedWombat Yes, you can look at the [Errors](http://examples.strictquirks.nl/errors/) page on my own website. IE11 and Edge highlight all the lines, all other browsers (Chrome, Firefox etc) only the first one. – Mr Lister Jan 14 '18 at 19:22
  • @MrLister thanks - I concur with the results you state -IE11 highlights all and lines whilst Chrome highlights only the first. This is the first factual response as compared to the rest of the superstition. I don't mean to be disparaging about the other contributions, it is just that no-one else could giev a concrete example. – Vanquished Wombat Jan 14 '18 at 19:26
  • 1
    @VanquishedWombat That is because you were asking the wrong question. Had you asked "What can go wrong when I introduce this error into my webpage" instead, then you would have received different results. Now my example is just a result of it being an error - (i.e. different error handling in the browsers); it doesn't answer the question as stated as well as the existing answers do. – Mr Lister Jan 14 '18 at 19:53

3 Answers3

12

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.

KayakinKoder
  • 3,243
  • 3
  • 23
  • 37
  • 3
    "...or someone with a mental incapacity (e.g. Internet Explorer)" ahahaahah. Nice comparison. :) – sinisake Jan 13 '18 at 13:49
  • 1
    I think you devalue your response with the English thing. The answer by @rensvwalstijn is more factual. – Vanquished Wombat Jan 13 '18 at 14:31
  • 3
    @VanquishedWombat I think it would be a quite valuable analogy to anyone new to programming in general. And like sinisake I think it's funny. Downvote away, no comedy allowed on SO! – KayakinKoder Jan 13 '18 at 14:34
7

Specification says UNIQUE

HTML 4.01 specification says ID must be document-wide unique.

HTML 5 specification says the same thing but in other words. It says that ID must be unique in its home subtree, which is basically the document if we read the definition of it.

Avoid duplication

But since HTML renderers are very forgiving when it comes to HTML rendering they permit duplicate IDs. This should be avoided if at all possible and strictly avoided when programmatically accessing elements by IDs in JavaScript. I'm not sure what getElementById function should return when several matching elements are found? Should it:

  • return an error?
  • return first matching element?
  • return last matching element?
  • return a set of matching elements?
  • return nothing?

But even if browsers work reliably these days, nobody can guarantee this behavior in the future since this is against specification. That's why I recommend you never duplicate IDs within the same document.

This is an answer by Robert Koritnik at Software Engineering asked by danludwig
Question: Two HTML elements with same id attribute: How bad is it really?

Duplicate ids not allowed in HTML

That code is incorrect. 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 o 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.

~From Dan Ray

Duplicate ids and JavaScript

So if you use duplicate ids in your HTML many libraries will not work as expected. The most libraries will get the first id they find and return that element. When we look at pure JavaScript: the document.getElementById("idName"); should return in the case of multiple elements with the same id. It says it must return the first element, in tree order.

TessavWalstijn
  • 1,698
  • 1
  • 19
  • 36
3

Under what circumstances is it illegal for an HTML page to contain elements with duplicate ID attributes?

It is illegal in any circumstances as per the specification:

When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element's tree [...].


As a developer who has worked with HTML for many years, I am aware that the intention is that element ids should be unique - what I am asking is for the practical negative effects of duplicate ids.

The CSS selector specification does not define how to handle documents with non-unique ids, as far as I can tell. So you cannot safely use id selectors in CSS in those cases.

The id attribute is also used to navigate to fragments (aka "anchors"). According to the specification, the browser should navigate to the "first such element in tree order". But that might conflict with which element actually comes first from top to bottom. I.e. your layout could conflict with the actual fragment link.


Granted, getElementByID() style functions in jquery etc might return arrays rather than a single element and this could cause issues when the developer had not anticipated this case. However, as far as I know, such functions will continue to operate so clearly they are not a breaking-effect of id duplicates.

That is clearly wrong, getElementByID() never returns an array. As per the specification:

The getElementById(elementId) method, when invoked, must return the first element, in tree order, within context object’s descendants, whose ID is elementId, and null if there is no such element otherwise.

Your expectation is also wrong in the case of jQuery:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.


There is really no reason to violate the specification in this case, you don't gain anything by doing it. While your pages won't completely break, you could run into problems with CSS, fragment links, and probably other things. In addition, your documents will be invalid and duplicate ids might confuse other people that have to maintain your code.

str
  • 42,689
  • 17
  • 109
  • 127