HTML/CSS/JS

HTML Class vs. ID: What’s the Difference (And When to Use Each)

In HTML, class is used to style or select multiple elements, while id uniquely identifies a single element—each with different syntax for use in CSS and JavaScript.

April 3, 2025

If you're learning HTML and CSS, you've probably seen class and id everywhere—but what's the actual difference?

And when should you use one over the other?

Let’s break it down with simple explanations and examples.

The Basic Idea

  • Class is like a label you can give to many elements.
  • ID is a unique name meant for one specific element.

Think of it like this:

  • Class = a team jersey (multiple players can wear it)
  • ID = a personal name tag (only one per person)

Example in HTML

<!-- Class example -->
<div class="box">Box 1</div>
<div class="box">Box 2</div>

<!-- ID example -->
<div id="special-box">I’m unique</div>

You can reuse the class .box as many times as you want, but there should only be one element with the ID special-box.

How CSS Targets Them

/* Class selector: use a dot */
.box {
  background-color: lightblue;
}

/* ID selector: use a hash */
#special-box {
  border: 2px solid black;
}

Use a dot for class (e.g. .box)
Use a hash for ID (e.g. #special-box)

How JavaScript Targets Them

// Target a class
const allBoxes = document.querySelectorAll('.box');

// Target an ID
const specialBox = document.querySelector('#special-box');

Classes let you work with groups of elements. IDs let you target one specific thing.

When to Use Each

Use class when:

  • You want to style multiple elements the same way
  • You want to group elements (e.g., all buttons)

Use id when:

  • You need a unique identifier (e.g., to scroll to a section)
  • You’re targeting one element with JavaScript

Quick Recap

Here’s a quick side-by-side comparison:

  • Reusable:
    • class: Yes, you can use it on many elements.
    • id: No, it should be unique per page.

  • CSS Selector:
    • class: Use a dot like .classname
    • id: Use a hash like #idname

  • JavaScript Selector:
    • class: Use document.querySelectorAll('.classname') to select all matching elements.
    • id: Use document.querySelector('#idname') to select a specific element.

Key Takeaway

Both class and id are useful, and knowing when to use each makes your HTML and CSS cleaner and more powerful.

If you're ever unsure, ask yourself: “Will I use this more than once?” If yes, go with a class.