In this article:
It’s possible to have more than one of the same ID in a page. Try this: when
querySelectorAll is used with an ID selector, will it return one result, or multiple results?
ids are unique. Reality: multiple elements can have the same ID.
If an element has an ID, that ID will be a global variable stored in
ID’s can cause confusion in CSS specificity. When ID’s are used for styling, it will have a side effect of increasing the specificity of the CSS rules. Let’s start with a simple HTML document with ID’s and classes:
color: white rule doesn't seem to work in this example. Try this in the Codepen demo.
#register-page a) takes precedence over the second selector (
.register-actions a) because it uses an ID. As a result, the color doesn't turn to white.
Overloaded semantics. Some projects use ID selectors (eg,
Difficult to test. It can be a bit awkward to test, possibly needing a mock
#submit-form element for it.
#submit-form ID used for styling, adding behaviours, or test targets? Often: maybe all of the above.
data-disable-on-submit attribute can be added to any form and for it to pick up the behaviour.
For targeting elements in tests, consider querying using:
[alt] text (for images)
Despite all these, ID’s are still useful in a number of cases.
introduction, lets the link scroll to where the content is.
aria-labelledby uses ID's to refer to another element.