Both id and class are HTML attributes used to identify and style elements, but they differ in uniqueness, usage, and purpose.
1️⃣ id Attribute
- Unique identifier for a single element on the page.
- Can be used for CSS styling, JavaScript access, or anchor links.
- Must not be repeated on the same page.
Example:
<div id="header">This is the header</div>
<style>
#header {
background-color: lightblue;
}
</style>
2️⃣ class Attribute
- Can be shared by multiple elements.
- Used to group elements for styling or scripting.
- Flexible for CSS styling, JavaScript selection, or applying behaviors.
Example:
<p class="highlight">First paragraph</p>
<p class="highlight">Second paragraph</p>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
🔹 Key Differences
| Feature | id |
class |
|---|---|---|
| Uniqueness | Must be unique | Can be shared by many |
| Usage in CSS | #id selector |
.class selector |
| JavaScript Access | getElementById |
getElementsByClassName / querySelectorAll |
| Purpose | Single element | Group of elements |
💡 In Short:
Use
idfor a unique element andclassfor multiple elements sharing the same styling or behavior.