HTML id global attribute
Theid
global attribute defines an identifier (ID) that must be unique within the entire document.
Try it
<p>A normal, boring paragraph. Try not to fall asleep.</p><p>The most exciting paragraph on the page. One of a kind!</p>
#exciting { background: linear-gradient(to bottom, #ffe8d4, #f69d3c); border: 1px solid #696969; padding: 10px; border-radius: 10px; box-shadow: 2px 2px 1px black;}#exciting::before { content: "ℹ️"; margin-right: 5px;}
Syntax
An ID attribute's value must not containASCII whitespace characters. Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to theclass
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 likeDocument.querySelector()
or in CSS stylesheets, ID attribute values must be validCSS identifiers. This means that if an ID attribute value is not a valid CSS identifier (for example,my?id
or1234
) then it must be escaped before being used in a selector, either using theCSS.escape()
method ormanually.
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 likewindow.1234
. However, you can access it usingwindow["1234"]
.
Description
The purpose of the ID attribute is to identify a single element when linking (using afragment identifier), scripting, or styling (withCSS).
You can access elements with ID attributes as global properties of thewindow
object, where the property name is the ID value, and the property value is the corresponding element. For example, given this markup:
<p></p>
You can access this paragraph element in JavaScript using the following code:
const content = window.preamble.textContent;
Warning:Relying on thewindow["id-value"]
orwindow.idValue
pattern is dangerous and discouraged because it can lead to unexpected conflicts with existing or future APIs in the browser.For example, if a browser introduces a built-in global property namedpreamble
in the future, your code may no longer be able to access the HTML element.To avoid such conflicts, always use theDocument.getElementById()
orDocument.querySelector()
method to access elements by ID.
Specifications
Specification |
---|
HTML # global-attributes:the-id-attribute-2 |
Browser compatibility
See also
- Allglobal attributes.
Element.id
that reflects this attribute.- The
Document.getElementById
method. - CSSID selectors.