Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ID have to be unique in the whole page?

Tags:

html

css

I am using jQuery and I am just wondering, does ID have to be always unique in the whole page? Class, I know, can be repeated as many times as you like, what about ID?

like image 689
good_evening Avatar asked Feb 26 '12 16:02

good_evening


People also ask

Does Id have to be unique?

The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.

Why is it important for the IDs of page elements to be unique?

Remember: A webpage element has certain inalienable rights; having a unique ID is one of them. Prevent html element identity theft by ensuring that every element on your webpage that needs an ID has a unique one.

Can you have spaces in IDs?

id 's value must not contain whitespace (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the class attribute, which allows space-separated values, elements can only have one single ID value.

How many times can an ID attribute be used on a page?

An element can't have more than one ID and an ID can't be used more than once in a page.


2 Answers

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.

like image 113
FatalError Avatar answered Nov 07 '22 21:11

FatalError


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.

like image 43
Константин Ван Avatar answered Nov 07 '22 21:11

Константин Ван