id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).
Warning: This attribute's value is an opaque string: this means that web authors should not rely on it to convey human-readable information (although having your IDs somewhat human-readable can be useful for code comprehension, e.g. consider
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.
Technically, the value for an
id attribute may contain any character, except whitespace characters. However, to avoid inadvertent errors, only ASCII letters, digits,
'-' should be used, and the value for an
id attribute should start with a letter.
. has a special meaning in CSS (it starts a class selector). While valid, unless you are careful to escape it when used as part of a CSS selector, it won't be recognized as part of the element's
id. The same applies to the
querySelectorAll() parameters, which use the same selector syntax. It is easy to forget to do this, resulting in bugs in your code that could be hard to detect.
id starting with a digit (E.g.,
1234-322-678) or a hyphen followed by a digit (E.g.,
- CSS ID selectors accept any CSS identifier. If the
idstarts with a digit or one hyphen immediately followed by a digit, both the hyphen and digit must be escaped in CSS. For example, while
id="-3Pi"are valid in HTML, the
idselectors must be escaped. The element with these
idvalues can be targeted in CSS with
#\2D \33 pi.
- Any valid HTML
Document.querySelector()and similar methods using CSS-selector-style queries will not find them unless you escape them. (See this page for an example.)
- Such an
1234is not a global variable, and you have to use
windowinstead to get the element with
id="1234". This is slightly inconvenient as you have to create the variable with an extra step:
const element = window.
|HTML Standard |
BCD tables only load in the browser