Explain Codes LogoExplain Codes Logo

What characters are allowed in DOM IDs?

html
id-attributes
utf-16-encoding
xml-namespaces
Alex KataevbyAlex KataevยทSep 6, 2024
โšกTLDR

DOM IDs in HTML start with letters (A-Z/a-z) and can contain letters, digits (0-9), hyphens (-), underscores (_), colons (:), and periods (.):

<div id="id-123"></div> <!-- That's valid. You're good to go! ๐Ÿ‘ -->

Numeric or special characters shouldn't initiate the IDs:

<div id="123abc"></div> <!-- Whoa! That's a no-no ๐Ÿ˜… -->

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.