Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 122 ยท Page Structure and Layout

Classes

Use the class attribute to group elements for CSS and JavaScript. Learn multiple classes, class selectors, classList methods and naming conventions that scale.

You've already used class in a few examples to point CSS at specific elements. It's one of the most-used attributes in HTML, and for good reason: a class lets you say "these elements belong together" and then style them or script them as a group.

This lesson covers the class attribute properly: how to write one or several classes, how CSS selects them, how JavaScript adds and removes them with classList, and how to name them so a stylesheet stays readable as a site grows.

The class attribute

class is a global attribute, so it works on every element. Its value is a name you make up:

HTML
<p class="warning">The bridge is closed for repairs until Friday.</p>

Any number of elements can share a class. That is the key difference from id, which must be unique (you'll learn about ids in the next lesson). A class describes a kind of thing; an id names one thing.

Classes do nothing by themselves. They are labels that CSS and JavaScript can look for.

Styling with class selectors

In CSS, a dot followed by the class name selects every element with that class:

One class, many elements

One rule styles every sold-out item, whether it's a list item or a paragraph. Move class="sold-out" to a different item and the styling follows.

You can also combine an element name with a class to narrow the match:

CSS
li.sold-out { โ€ฆ }   /* only <li> elements with the class */
.menu a { โ€ฆ }       /* any <a> inside an element with class "menu" */

Multiple classes

An element can have several classes. Separate them with spaces:

HTML
<button class="btn btn-primary btn-large">Book a table</button>

This element has three classes: btn, btn-primary and btn-large. Each class can carry one aspect of the design, and you mix them like building blocks:

Combining classes

Note the last CSS rule: .btn.btn-primary.btn-large (no spaces) matches only elements that have all three classes. With spaces, .btn .btn-primary would mean something different: a .btn-primary inside a .btn.

Order doesn't matter in the attribute. class="btn btn-primary" and class="btn-primary btn" are identical. When two rules conflict, CSS decides by specificity and by which rule comes later in the stylesheet, never by the order of the class names in your HTML.

Rules for class names

The HTML spec allows almost anything in a class name; it's simply a space-separated list of tokens. In practice, follow these rules to avoid trouble:

  • No spaces inside a name. A space starts a new class. class="sold out" gives two classes, sold and out.
  • Class names are case-sensitive. .Featured doesn't match class="featured". Sticking to lowercase avoids the problem.
  • Start with a letter. Names like 2col are valid HTML, but a CSS selector can't begin with a digit without escaping (.\32 col). Write two-col instead.
  • Use letters, digits, hyphens and underscores. Other characters work but must be escaped in CSS selectors.

Naming classes well

A good class name describes what something is or does, not how it looks right now:

Fragile Better Why
red-text error-message The design might change to orange; it will still be an error.
left-column sidebar On phones, the "left" column moves below the content.
big-font lead Describes its role: the opening paragraph.

Most teams also pick a naming convention so class names are predictable. Two common styles:

  • Kebab-case, all lowercase with hyphens: product-card, product-card-title. It matches how CSS properties are written and is the most common choice.
  • BEM (Block, Element, Modifier): card (block), card__title (an element inside the block), card--featured (a variation). The double underscores and hyphens look unusual at first, but they make the relationship between classes clear at a glance.
HTML
<article class="card card--featured">
  <h3 class="card__title">Kayak tour</h3>
  <p class="card__price">$45</p>
</article>

Utility-first frameworks take a third approach, with many tiny single-purpose classes like p-4 or text-center. Whatever you choose, be consistent across the whole project.

Classes in JavaScript

JavaScript uses classes in two ways: to find elements and to change their state.

Finding elements by class

JavaScript
// All matching elements (a static NodeList)
const items = document.querySelectorAll('.sold-out');

// The first matching element, or null
const firstCard = document.querySelector('.card');

querySelector and querySelectorAll accept any CSS selector, so everything you've learned about class selectors works here too. (There's also the older getElementsByClassName('sold-out'), which returns a live collection.)

Changing classes with classList

Every element has a classList property with handy methods:

Method What it does
add('name') Adds a class (does nothing if it's already there).
remove('name') Removes a class.
toggle('name') Adds it if missing, removes it if present. Returns true if it's now present.
contains('name') Returns true or false.
replace('old', 'new') Swaps one class for another.

The usual pattern is to define the look in CSS and only switch the class in JavaScript. Your script never has to know what "highlighted" looks like:

Toggling classes with classList

In a real interface, use real controls. Clickable <div> elements keep this demo short, but they can't be reached with the keyboard. For a real checklist, use checkboxes, as you'll learn in Checkboxes and Radio Buttons.

You may also see element.className, which reads or replaces the whole attribute as one string. It's easy to wipe out other classes by accident with it, so prefer classList. The DOM lesson covers these APIs in more depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you give an element the classes card and featured?

    Classes are separated by spaces inside one class attribute. A second class attribute would be ignored.
  2. 2. What does the CSS selector .card.featured match?

    With no space between them, the selectors must both match the same element. A space would mean "inside".
  3. 3. Which classList method adds a class if it's missing and removes it if it's present?

    toggle() flips the class and returns true if the class is present afterward. There is no switch() method.
  4. 4. Which class name is the most robust choice for a box of error text?

    Naming by purpose keeps the name accurate even when the design changes. red-box describes today's look, and Box1 describes nothing.

Summary

  • class is a global attribute that puts elements into named groups; many elements can share a class.
  • An element can have several space-separated classes; their order in the attribute doesn't matter.
  • .name selects by class in CSS; .a.b requires both classes on the same element.
  • Class names are case-sensitive; use lowercase, start with a letter and avoid spaces.
  • Name classes by purpose and pick a convention (kebab-case or BEM) for the whole project.
  • In JavaScript, find elements with querySelectorAll('.name') and change classes with classList.add, remove, toggle, contains and replace.

Next lesson: IDs.