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 | Yes | No |
| Reusable | No | Yes |
| CSS selector | #id | .class |
| JavaScript | getElementById() | getElementsByClassName() |
| Use case | Single element | Group of elements |
Rule of thumb
Use
idfor unique elementsUse
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
idon multiple elements - Confusing
idwithclass Forgetting#in CSS- Overusing
idfor styling instead ofclass
Key Points to Remember
iduniquely identifies one elementSelected using
#in CSSUsed heavily in JavaScript
Ideal for anchors & unique layout parts
Never repeat the same
id
