ID's and Classes
Learn to use id and class attributes to identify and group HTML elements for CSS and JavaScript.
IDs and Classes
The id and class attributes are how you identify and group HTML elements for targeting with CSS and JavaScript.
The id Attribute
An id gives an element a unique identifier. Each id must be unique on the page — no two elements can share the same id.
<h1 id="main-title">Welcome</h1>
<div id="hero-section">
<p>Hero content here.</p>
</div>
The class Attribute
A class groups elements together. Multiple elements can share the same class, and one element can have multiple classes.
<p class="intro">First paragraph.</p>
<p class="intro highlight">Second paragraph (two classes).</p>
<p class="intro">Third paragraph.</p>
id vs class
| Feature | id | class |
|---|---|---|
| Uniqueness | Must be unique on the page | Can be reused on many elements |
| Multiple values | One id per element | Multiple classes per element |
| CSS selector | #id-name | .class-name |
| JS selector | getElementById() | getElementsByClassName() |
| Specificity | Higher (overrides class styles) | Lower |
| Best for | Unique elements (header, footer) | Repeated patterns (cards, buttons) |
Using IDs and Classes in CSS
<style>
/* ID selector — targets ONE specific element */
#main-title {
color: #6c5ce7;
font-size: 2.5rem;
}
/* Class selector — targets ALL elements with this class */
.intro {
font-size: 1.1rem;
line-height: 1.7;
color: #555;
}
.highlight {
background-color: #fffbcc;
padding: 4px 8px;
}
</style>
Using IDs and Classes in JavaScript
<script>
// Select by ID
const title = document.getElementById('main-title');
title.textContent = 'Updated Title';
// Select by class
const intros = document.querySelectorAll('.intro');
intros.forEach(p => p.style.color = 'blue');
</script>
Naming Best Practices
- Use lowercase with hyphens:
hero-section,nav-bar,card-title - Be descriptive:
product-cardis better thanbox1 - Don't start with a number:
section-1is okay,1-sectionis not - Avoid unnecessary IDs — use classes by default, IDs only when you truly need uniqueness
Anchor Links with IDs
IDs also enable anchor links — clicking a link scrolls to that element:
<a href="#contact">Jump to Contact</a>
<!-- Further down -->
<section id="contact">
<h2>Contact Us</h2>
</section>
Key Takeaways
idis unique — only one element per pageclassis reusable — multiple elements can share it- Use
#idand.classselectors in CSS - Prefer classes over IDs for styling
- Use descriptive, hyphenated names