Junior
When should you use id, and when class in HTML?
sobes.tech AI
Answer from AI
id is used as a unique identifier for an element on the page. In a document, only one element can have the same id value. It is often used for linking labels to input fields (<label for="...">) or for anchors (<a href="#...">). It can also be useful for quick access to an element via JavaScript (document.getElementById(...)).
class is used for grouping elements with common styles or behavior. Multiple elements can share the same class. This is the primary way to apply CSS styles. The same element can have multiple classes separated by spaces.
| Usage | Identifier (id) |
Class (class) |
|---|---|---|
| Uniqueness | Strictly unique on the page | Can be repeated |
| Number per element | One | Multiple allowed |
| Main use | Unique link, anchor, JavaScript access | Grouping for styles and JS |
| CSS selector | # |
. |