Does ID have to be unique in the whole page?

Yes, it must be unique.

HTML4:

https://www.w3.org/TR/html4/struct/global.html#h-7.5.2

Section 7.5.2:

id = name [CS] This attribute assigns a name to an element. This name must be unique in a document.

HTML5:

https://www.w3.org/TR/html5/dom.html#element-attrdef-global-id

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.


Does an ID have to be unique in the whole page?

No.

Because the HTML Living Standard of September 7, 2021, clearly states:

The class, id, and slot attributes may be specified on all HTML elements. ……. When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element’s tree and must contain at least one character. The value must not contain any ASCII whitespace.

and a page may have several DOM trees. It does, for example, when you’ve attached (Element.attachShadow()) a shadow DOM tree to an element.

A document tree and its underlying shadow trees


TL; DR

Does an ID have to be unique in the whole page?

No.

Does an ID have to be unique in a DOM tree?

Yes.


from mdn enter image description herehttps://developer.mozilla.org/en/DOM/element.id

so i guess it better be...


Technically, by HTML5 standards ID must be unique on the page - https://developer.mozilla.org/en/DOM/element.id

But I've worked on extremely modular websites, where this is completely ignored and it works. And it makes sense - the most surprising part.

We call it "componentization"

For example, you might have a component on your page, which is some kind of widget. It has stuff inside with their own unique IDs eg "ok-button"

Once there are many of these widgets on the page, you technically have invalid HTML. But it makes perfect sense to componentize your widgets so that they each, internally, reference their own ok button eg if using jquery to search from it's own root it might be: $widgetRoot.find("#ok-button")

This works for us, though technically IDs shouldn't be used at all, once they're not unique.

As cited above, even YouTube does it, so it's not so renegade.


Browsers used to be lenient on this (many years ago when css was young) and allow the ID to be used more than once. They have become more strict.

However, yes ID's are to be unique and only used once.

If you need to use css formatting more than once use CLASS.