HTML id Attribute
🌐 HTML id Attribute
It is commonly used for CSS styling, JavaScript access, and page navigation (anchors).
1. What Is the id Attribute?
-
Assigns a unique name to an HTML element
-
Must be unique (only one element per page)
-
Used with CSS (
#) and JavaScript
2. Basic Example
HTML
CSS
✔ Only the element with id="intro" gets styled
3. Using id with <div>
✔ Very common for page layout
4. id in JavaScript (Very Common)
✔ Direct access to a single element
5. id for Page Navigation (Anchor Links)
✔ Clicking the link scrolls to the element with that id
6. id vs class (Important Difference)
| Feature | id |
class |
|---|---|---|
| Unique | ✔ | ❌ |
| Reusable | ❌ | ✔ |
| CSS selector | #id |
.class |
| JavaScript | getElementById() |
getElementsByClassName() |
| Use case | Single element | Group of elements |
👉 Rule of thumb
-
Use
idfor unique elements -
Use
classfor repeated styling
7. Naming Rules & Best Practices
✔ Must be unique
✔ Case-sensitive
✔ No spaces (use - or _)
✔ Start with a letter
Good
Bad ❌
❌ Common Mistakes
❌ Using same id on multiple elements
❌ Confusing id with class
❌ Forgetting # in CSS
❌ Overusing id for styling instead of class
🧠 Key Points to Remember
-
iduniquely identifies one element -
Selected using
#in CSS -
Used heavily in JavaScript
-
Ideal for anchors & unique layout parts
-
Never repeat the same
id
