Skip to content

getElementById should not return the first but no element if id exists multiple times #1361

Open
@kkmuffme

Description

@kkmuffme

What is the issue with the DOM Standard?

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

An element can have an associated unique identifier (ID)
This specification makes ID a concept of the DOM and allows for only one per element, given by an id attribute.

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

The getElementById(elementId) method steps are to return the first 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions