Question

How to Change an Element's Class with JavaScript

javascripthtmldom

Question

How can I change the class of an HTML element using JavaScript in response to onclick or other events?

For example, I want an HTML element to update its CSS class when a user clicks it or when another event occurs.

Short Answer

By the end of this page, you will understand how JavaScript changes CSS classes on HTML elements, how to respond to events like clicks, and when to use className versus classList methods such as add(), remove(), toggle(), and replace().

Concept

JavaScript can modify the class attribute of an HTML element at runtime. This is one of the most common ways to update a page's appearance or behavior without reloading it.

CSS classes usually control styling:

.active {
  background: blue;
  color: white;
}

When JavaScript adds or removes a class, the browser immediately re-applies the CSS rules for that element.

For example, if a button gets the active class after a click, it might change color, become visible, animate, or indicate selection.

There are two main ways to change classes:

  1. element.className

    • Replaces the entire class string.
    • Simple, but easy to overwrite existing classes by mistake.
  2. element.classList

    • A modern and safer API for working with individual classes.
    • Lets you add, remove, toggle, check, and replace classes.

Why this matters in real programming:

  • Show or hide menus
  • Mark selected items
  • Highlight form errors
  • Switch themes like dark mode
  • Trigger animations
  • Update UI state after API responses

In practice, classList is usually the best choice because it works with one class at a time and avoids accidental overwrites.

Mental Model

Think of an HTML element's classes like sticky labels on a box.

  • className means replacing the whole set of labels at once.
  • classList.add("active") means placing one new label on the box.
  • classList.remove("active") means peeling one label off.
  • classList.toggle("active") means adding the label if it is missing, or removing it if it is already there.

Events such as clicks are like signals telling JavaScript when to update those labels.

Take Quiz

Syntax and Examples

Core syntax

Using classList

element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");
element.classList.replace("old-class", "new-class");

Using className

element.className = "active";

This replaces all existing classes with active.

Example: change class on click

<button id="myButton" class="btn">Click me</button>
.btn {
  background: gray;
  color: white;
}

.active {
  background: green;
}
const button = document.getElementById("myButton");

button.addEventListener("click", function () {
  button.classList.add("active");
});

What this does

  • The button starts with the class btn
  • When clicked, JavaScript adds active
  • The final class list becomes btn active
  • CSS for .active is now applied

Example: toggle class on click

button.addEventListener("click", function () {
  button.classList.toggle("active");
});

This is useful when you want something to switch on and off, such as:

  • opening and closing a menu
  • selecting and unselecting an item
  • enabling dark mode

Example: inline onclick

<button onclick="this.classList.toggle('active')">Click me</button>

This works, but in real projects, addEventListener is usually preferred because it keeps JavaScript separate from HTML.

Step by Step Execution

Consider this example:

<div id="card" class="card">Hello</div>
const card = document.getElementById("card");

card.addEventListener("click", function () {
  card.classList.toggle("highlight");
});

Step by step:

  1. The browser loads the HTML.
  2. JavaScript runs document.getElementById("card").
  3. The variable card now refers to the <div> element.
  4. addEventListener("click", ...) tells the browser to wait for a click on that element.
  5. When the user clicks the <div>, the callback function runs.
  6. card.classList.toggle("highlight") checks whether highlight is already present.
    • If not present, it adds it.
    • If present, it removes it.
  7. The browser updates the element's class attribute.
  8. CSS styles connected to .highlight are applied or removed immediately.

If the element starts as:

<div id="card" class="card">Hello</div>

After one click, it becomes:

<div id="card" class="card highlight">Hello</div>

After another click, it goes back to:

<div id="card" class="card">Hello</div>

Real World Use Cases

Changing classes with JavaScript is used everywhere in web development.

Common examples

  • Navigation menus: add an open class when a mobile menu button is clicked
  • Form validation: add an error class to invalid inputs
  • Tabs and accordions: add an active class to the selected tab
  • Dark mode: toggle a dark class on the body
  • Loading states: add a loading class while waiting for an API response
  • Animations: add a class like fade-in to start a CSS animation
  • Selected items: mark a chosen product, card, or list row

Example: showing and hiding a menu

const menuButton = document.getElementById("menuButton");
const menu = document.getElementById("menu");

menuButton.addEventListener("click", function () {
  menu.classList.toggle("open");
});

Here, CSS decides what .open means, such as display: block or a slide-down effect.

Take Quiz

Real Codebase Usage

In real projects, developers usually use class changes to represent UI state.

Common patterns

Guard clauses

Check that an element exists before changing its class:

const modal = document.getElementById("modal");

if (!modal) {
  return;
}

modal.classList.add("visible");

This prevents errors if the element is missing.

Event-driven UI updates

document.getElementById("saveButton").addEventListener("click", function () {
  document.body.classList.add("saving");
});

Validation states

function showError(input) {
  input.classList.add("error");
}

function clearError(input) {
  input.classList.remove("error");
}

Conditional classes

if (user.isAdmin) {
  document.body.classList.add("admin-mode");
}

Replacing one state with another

statusBox.classList.replace("pending", "success");

This is cleaner than manually removing one class and adding another.

Why this is common

It keeps styling in CSS and logic in JavaScript. JavaScript decides when state changes, and CSS decides how that state looks.

Common Mistakes

1. Overwriting all classes accidentally

Broken example:

element.className = "active";

If the element originally had:

<div class="card large"></div>

it now loses card and large.

Better:

element.classList.add("active");

2. Using . in the class name

Broken example:

element.classList.add(".active");

Class names in JavaScript should not include the dot.

Correct:

element.classList.add("active");

3. Running code before the element exists

Broken example:

const button = document.getElementById("myButton");
button.classList.add("active");

If the script runs before the HTML is loaded, button may be null.

How to avoid it:

  • Put the script at the end of the <body>
  • Or wait for the DOM to load
document.addEventListener("DOMContentLoaded", function () {
  const button = document.getElementById("myButton");
  button.classList.add("active");
});

4. Forgetting that toggle() switches both ways

element.classList.toggle("active");

This does not always add the class. If the class is already present, it removes it.

Use add() if you always want it present.

5. Mixing inline event handlers with larger scripts

This works:

<button onclick="this.classList.add('active')">Click</button>

But it becomes harder to manage in bigger applications.

Prefer:

button.addEventListener("click", function () {
  button.classList.add("active");
});

6. Trying to use classList on multiple elements at once

Broken example:

const items = document.querySelectorAll(".item");
items.classList.add("active");

querySelectorAll() returns a collection, not a single element.

Correct:

const items = document.querySelectorAll(".item");

items.forEach(function (item) {
  item.classList.add("active");
});

Comparisons

ApproachWhat it doesBest forRisk
element.className = "active"Replaces the full class stringVery simple casesCan remove existing classes
element.classList.add("active")Adds one classMost common updatesLow
element.classList.remove("active")Removes one classClearing a stateLow
element.classList.toggle("active")Adds or removes based on current stateOn/off UI behaviorCan be confusing if you always want add
element.classList.replace("old", "new")Swaps one class for anotherState transitionsRequires old class to exist

onclick vs addEventListener

MethodExampleWhen to use
Inline onclick<button onclick="doSomething()">Small demos or quick tests
addEventListenerbutton.addEventListener("click", doSomething)Real projects and cleaner code

addEventListener is more flexible because you can attach multiple handlers and keep JavaScript out of your HTML.

Take Quiz

Cheat Sheet

// Select an element
const element = document.getElementById("myElement");

// Add a class
element.classList.add("active");

// Remove a class
element.classList.remove("active");

// Toggle a class
element.classList.toggle("active");

// Replace a class
element.classList.replace("hidden", "visible");

// Check if a class exists
element.classList.contains("active");

// Replace all classes
element.className = "active";

Rules to remember

  • Use classList for most class changes
  • Do not include . in class names
  • className replaces the entire class string
  • toggle() adds if missing, removes if present
  • querySelectorAll() returns multiple elements, so loop over them
  • Make sure the element exists before changing its class

Event example

element.addEventListener("click", function () {
  element.classList.toggle("active");
});

FAQ

How do I change a class when a button is clicked in JavaScript?

Use an event listener and classList:

button.addEventListener("click", function () {
  element.classList.add("active");
});

What is the difference between className and classList?

className replaces the whole class string. classList lets you safely add, remove, or toggle individual classes.

How do I toggle a class on click?

Use:

element.classList.toggle("active");

This adds the class if it is missing and removes it if it is already there.

Can I change a class using onclick in HTML?

Yes:

<button onclick="this.classList.toggle('active')">Click</button>

But addEventListener is usually better for maintainable code.

Why is classList.add() not working?

Common reasons:

  • The element was not found
  • The script ran before the DOM loaded
  • You used the wrong selector
  • You accidentally included a dot, like .active

How do I remove one class without affecting others?

Use:

element.classList.remove("active");

This removes only that class.

Can I change classes on multiple elements?

Yes. Loop through the selected elements:

document.querySelectorAll(".item").forEach(function (item) {
  item.classList.add("active");
});
Take Quiz

Mini Project

Description

Build a simple theme switcher that changes the page appearance when a button is clicked. This demonstrates how to select elements, listen for events, and toggle CSS classes to update the UI state.

Goal

Create a button that toggles a dark-mode class on the page so the user can switch between light and dark themes.

Requirements

[ "Create a button the user can click to change the theme.", "Add CSS for a normal theme and a dark theme.", "Use JavaScript to toggle a class on the page.", "Keep the existing classes intact when switching themes." ]

Take Quiz

Keep learning

Related questions

View more