Does an ID have to be unique in the whole page?
No.
Because the HTML Living Standard of March 15, 2022, clearly states:
The
class
,id
, andslot
attributes may be specified on all HTML elements. …….
When specified on HTML elements, theid
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.
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.