[whatwg/dom] getElementById should not return the first but no element if id exists multiple times (Issue #1361)

kkmuffme created an issue (whatwg/dom#1361)

### What is the issue with the DOM Standard?

https://dom.spec.whatwg.org/#concept-id

>An [element](https://dom.spec.whatwg.org/#concept-element) can have an associated **unique identifier** (ID)
>This specification makes [ID](https://dom.spec.whatwg.org/#concept-id) a concept of the DOM and **allows for only one** per [element](https://dom.spec.whatwg.org/#concept-element), given by an [id attribute](https://dom.spec.whatwg.org/#concept-named-attribute).

But then:
https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid

>The getElementById(elementId) method steps are to **return the first** [element](https://dom.spec.whatwg.org/#concept-element)

While there are historical reasons (= fixing people's mistakes) for this, this behavior is inconsistent and can have massive side-effects, since it's asserted that it's unique. However, this uniqueness is purely stated, but contradicts practical behavior, since there is not a single function/method that complies with this uniqueness, is there?

Therefore either
a) remove the "unique" from the spec for id - then what's the point of "id" to begin with? It's essentially identical to class and obsolete.
**or**
b) enforce the "unique" for the id in getElementById - if there are multiple elements with the same ID, it should not return the first, but no elements (since `null` is already reserved for no elements found, it could possibly return `false` in that case)
While this is going to hurt a lot initially, I think this would be the right thing to do, since that's how it works everywhere else too. Inserting a non-unique ID into a database? You get an error.

Why that matters?
The uniqueness property allows skipping certain validations that are necessary for non-unique elements. e.g. you provide a button to copy something to the user's clipboard. Since the docs state that IDs are unique, you can be sure it actually copied what you wanted - except that's obviously wrong, since something else could have used the same ID somewhere in the document before your id, and the user would have copied something completely different


-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1361
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/1361@github.com>

Received on Wednesday, 19 February 2025 12:32:15 UTC