What characters are allowed in DOM IDs?
DOM IDs in HTML start with letters (A-Z/a-z) and can contain letters, digits (0-9), hyphens (-), underscores (_), colons (:), and periods (.):
Numeric or special characters shouldn't initiate the IDs:
Ensure uniqueness, as IDs need to be unparalleled within the same document.
HTML vs XHTML ID rules
HTML and XHTML have unique character allowances for ID attributes. HTML provides more versatility, while XHTML complies with stricter XML's Name production rules.
Quick to tricky: characters and strings
UTF-16: DOMString representation
JavaScript uses DOMString
to represent IDs with UTF-16 encoding, enabling the use of almost any UTF-16 character in your IDs. However, comply with the HTML rules to avoid glitches.
Special characters: To be or not to be
Despite the allure, avoid unlisted special characters, including spaces and punctuation marks other than hyphens and underscores.
Colons encounter: XML namespaces
Colons are significant in XHTML IDs due to their role in XML Namespaces. If your document is XHTML, tread lightly here!
Making your life easier
HTML legacy quirks
Legacy systems sometimes balk at certain characters. For the smoothest sailing, stick to the W3C specification.
Accessibility-first mind-set
Remember, screen readers, accessibility tools and ARIA landmark roles may use your IDs, so make them as meaningful and descriptive as possible.
Was this article helpful?