id
The id
global attribute defines an identifier (ID) which must be unique in the whole document.
Try it
Description
The purpose of the ID attribute is to identify a single element when linking (using a fragment identifier), scripting, or styling (with CSS).
Elements with ID attributes are available as global properties. The property name is the ID attribute, and the property value is the element. For example, given markup like:
<p id="preamble"></p>
You could access the paragraph element in JavaScript using code like:
const content = window.preamble.textContent;
Syntax
An ID attribute's value must not contain ASCII whitespace characters. 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 other Unicode character. However, when used in CSS selectors, either from JavaScript using APIs like Document.querySelector()
or in CSS stylesheets, ID attribute values must be valid CSS identifiers. This means that if an ID attribute value is not a valid CSS identifier (for example, my?id
or 1234
) then it must be escaped before being used in a selector, either using the CSS.escape()
method or manually.
For this reason, it's recommended that developers choose values for ID attributes that are valid CSS identifiers that don't require escaping.
Also, not all valid ID attribute values are valid JavaScript identifiers. For example, 1234
is a valid attribute value but not a valid JavaScript identifier. This means that the value is not a valid variable name, so you can't access the element using code like window.1234
. However, you can access it using window["1234"]
.
Specifications
Specification |
---|
HTML Standard # global-attributes:the-id-attribute-2 |
Browser compatibility
BCD tables only load in the browser
See also
- All global attributes.
Element.id
that reflects this attribute.- The
Document.getElementById
method. - CSS ID selectors.