Both id
and class
can be used to identify HTML elements. Any HTML element that can be identified with an ID could be similarly identified if you added the ID as a class instead. I can see some vague contours of a semantic reason why id and classes are both nice to have, but it hardly seems justifiable if we could do the exact same thing with one of them. Am I missing some important usages of id
which cannot be done with class
?
Asked
Active
Viewed 170 times
-3

cmeeren
- 3,890
- 2
- 20
- 50
-
`"Am I missing some important usages of id"` - Yes. Namely that it *identifies* an element. `class`, along with lots of other attributes, *describes* an element. Such descriptions can be used to identify an element if they are coincidentally unique to that element, but they are never guaranteed or required to be. An identifier, however, is. And other parts of the HTML spec rely on it to be. – David Feb 26 '16 at 14:08
-
@Xufox: That question is about CSS, not HTML. – BoltClock Feb 26 '16 at 14:08
3 Answers
5
The ID attribute is used by HTML features like <label for="ID">
and aria-labelledby="ID"
that require a unique ID.

SLaks
- 868,454
- 176
- 1,908
- 1,964
2
In a conforming document, you can rely on an ID that is in use always pointing to exactly one element. You don't have this guarantee for a class since a class is designed for use by any number of elements.
There are numerous use cases that all rely on a unique ID, including but not limited to:
- Fragment identifiers (which can also be resolved with a named anchor but that feature has been deprecated in favor of just straight-up using IDs)
- The
for
attribute on thelabel
element document.getElementById()

BoltClock
- 700,868
- 160
- 1,392
- 1,356
-1
The concept is:
a Class can contain multiple elements while a id is a unique identifier.
So say you are designing a menu, you can add each button to a class and then style all the buttons at the same time.
In Javascript:
document.getElementById('');
document.getElementByClass('');
In JQuery:
$('#someId');
$('.someClass');
Hope this helps

Kickass
- 1,114
- 9
- 16
-
Doesn't answer the question, really. You could do the same with only classes. – cmeeren Feb 26 '16 at 14:22
-
I think you stated your response backwards but sure I guess you could, but do you really want to style each element individually? ID's are unique identifiers, while classes are grouping logic.Classes can return more then one element while IDs only return one element. This is really self explanatory, which is why I didn't go into depth about it. If you don't understand it after this simple explanation then you have to hit the books again because, you obviously don't understand coding. In the words of Einstein: If you can't explain it simply then maybe you don't understand it well enough... – Kickass Feb 28 '16 at 14:28