Question

How to Change an Element's Class with JavaScript

htmljavascriptdom

Question

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

Short Answer

By the end of this page, you will understand how JavaScript changes CSS classes on HTML elements, how to respond to user events like clicks, and when to use methods such as className and classList. You will also see practical examples, common mistakes, and a small project to help you practise.

Concept

JavaScript can modify the appearance and behavior of a webpage by changing the classes assigned to HTML elements. Since CSS classes control styling, changing a class lets you update the UI dynamically without rewriting styles inline.

For example, you might:

  • highlight a selected menu item
  • open and close a dropdown
  • show validation errors
  • switch between light and dark themes
  • mark a task as completed

There are two main ways to change classes in JavaScript:

1. element.className

This replaces the full class string on an element.

element.className = "active";

If the element already had other classes, they will be removed unless you include them too.

2. element.classList

This is the modern and safer way to work with classes.

It lets you:

  • add a class with add()
  • remove a class with remove()
  • toggle a class with toggle()
  • check for a class with contains()
  • replace a class with replace()
element.classList.add("active");
element.classList.remove("hidden");
element.classList.toggle("open");

This matters in real programming because class changes are one of the most common ways to update the interface in response to user interaction.

Mental Model

Think of an HTML element as a person wearing name tags.

  • The element is the person.
  • The class names are the tags attached to them.
  • CSS reads those tags and decides how the person should look.
  • JavaScript can remove one tag and attach another when something happens.

For example, if a button has the class inactive, CSS may make it gray. If JavaScript changes that class to active, CSS may make it green.

So JavaScript does not directly paint the button. It changes the labels, and CSS reacts to those labels.

Take Quiz

Syntax and Examples

Basic syntax

Using className

const box = document.getElementById("box");
box.className = "highlight";

This replaces all existing classes with highlight.

Using classList.add()

const box = document.getElementById("box");
box.classList.add("highlight");

This adds highlight without removing other classes.

Using classList.remove()

box.classList.remove("highlight");

Using classList.toggle()

box.classList.toggle("highlight");

If the class exists, it is removed. If it does not exist, it is added.

Example: change a class on click

<button id="themeButton">Toggle Highlight</button>
<div id="box" class="card">Hello</div>
.card {
  padding: 16px;
  background: lightgray;
}

.highlight {
  background: gold;
}
const button = document.getElementById("themeButton");
const box = document.getElementById("box");

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

What this does

  • The button listens for a click event.
  • When clicked, JavaScript toggles the highlight class on the div.
  • CSS updates the background color automatically.

Example: replacing one class with another

<p id="status" class="offline">Server status</p>
const status = document.getElementById("status");
status.classList.replace("offline", "online");

This is useful when only one state should be active at a time.

Step by Step Execution

Consider this example:

<button id="btn">Click me</button>
<div id="message" class="hidden">Welcome!</div>
.hidden {
  display: none;
}
const btn = document.getElementById("btn");
const message = document.getElementById("message");

btn.addEventListener("click", function () {
  message.classList.toggle("hidden");
});

Step by step

  1. JavaScript finds the button using document.getElementById("btn").
  2. JavaScript finds the message element using document.getElementById("message").
  3. The code attaches a click event listener to the button.
  4. At this point, the div has the class hidden, so it is not visible.
  5. When the user clicks the button, the function inside addEventListener runs.
  6. message.classList.toggle("hidden") checks whether hidden exists.
  7. Since hidden exists, JavaScript removes it.
  8. The CSS rule no longer applies, so the message becomes visible.
  9. If the button is clicked again, toggle() adds hidden back.
  10. The message becomes hidden again.

This pattern is very common for showing and hiding content.

Real World Use Cases

Changing classes with JavaScript is used in many everyday UI features:

User interaction

  • opening and closing menus
  • expanding accordions
  • switching tabs
  • highlighting selected items
  • marking checkboxes or tasks as complete

Form handling

  • adding an error class when validation fails
  • adding a success class after valid input
  • highlighting required fields

App state changes

  • toggling dark mode
  • showing loading states with a loading class
  • disabling or dimming elements visually
  • changing status indicators like online and offline

Responsive UI behavior

  • opening mobile navigation
  • showing modal dialogs
  • collapsing sidebars
  • animating panels with CSS transitions

Instead of manually changing many style properties, developers usually change one or two classes and let CSS handle the visual details.

Take Quiz

Real Codebase Usage

In real projects, developers usually prefer classList because it is clearer and less error-prone than rewriting the whole className string.

Common patterns

Guard clauses

Avoid changing classes if an element does not exist.

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

if (!modal) {
  return;
}

modal.classList.add("open");

Validation feedback

const emailInput = document.getElementById("email");

if (emailInput.value === "") {
  emailInput.classList.add("error");
} else {
  emailInput.classList.remove("error");
}

Early return inside event handlers

document.addEventListener("click", function (event) {
  const button = event.target.closest(".toggle-button");

  if (!button) {
    return;
  }

  button.classList.toggle("active");
});

State-based styling

A class often represents a state:

  • is-open
  • is-active
  • is-hidden
  • has-error
  • is-loading

This naming style makes code easier to read.

Separating behavior and style

Good codebases let JavaScript manage state and let CSS manage presentation.

panel.classList.add("is-open");
.is-open {
  transform: translateX(0);
}

This separation keeps code cleaner and easier to maintain.

Common Mistakes

1. Accidentally replacing all classes

Broken example:

element.className = "active";

If the element originally had card large, both are removed.

Better:

element.classList.add("active");

2. Forgetting the dot rules

When using classList, do not include a dot.

Broken example:

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

Correct:

element.classList.add("active");

The dot is used in CSS selectors, not class names stored in JavaScript.

3. Running code before the element exists

Broken example:

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

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

How to avoid it:

  • place the script at the end of the body, or
  • use DOMContentLoaded
document.addEventListener("DOMContentLoaded", function () {
  const box = document.getElementById("box");
  box.classList.add("active");
});

4. Using onclick everywhere

Inline event handlers work, but they mix HTML and JavaScript.

Less maintainable:

<button onclick="toggleBox()">Toggle</button>

Better:

button.addEventListener("click", toggleBox);

5. Toggling the wrong element

Sometimes beginners attach the listener to one element but change the class on another by mistake.

Check carefully which element you selected.

6. Assuming class changes work without CSS

Adding a class only matters if your CSS uses that class.

.active {
  color: red;
}

Without a matching CSS rule, the UI may not look different even though the class changed.

Comparisons

ApproachWhat it doesKeeps existing classes?Best use
element.className = "active"Replaces the full class stringNoWhen you want to fully overwrite classes
element.classList.add("active")Adds one classYesMost common way to enable a style
element.classList.remove("active")Removes one classYesRemoving a state or style
element.classList.toggle("active")Adds or removes a class automaticallyYesClick-based UI toggles
element.classList.replace("a", "b")Swaps one class for anotherYesMoving between known states

onclick vs addEventListener

MethodProsCons
onclick attribute in HTMLSimple for tiny demosMixes HTML and JavaScript, harder to scale
addEventListener()Cleaner, reusable, supports multiple listenersSlightly more code

In modern JavaScript, addEventListener() is usually the better choice.

Take Quiz

Cheat Sheet

Quick reference

Select an element

const el = document.getElementById("myElement");

Replace all classes

el.className = "active";

Add a class

el.classList.add("active");

Remove a class

el.classList.remove("active");

Toggle a class

el.classList.toggle("active");

Check whether a class exists

el.classList.contains("active");

Replace one class with another

el.classList.replace("inactive", "active");

Rules to remember

  • Use classList for most cases.
  • Do not include . in class names when using JavaScript methods.
  • className overwrites all classes.
  • Class changes only affect styling if CSS uses those classes.
  • Use addEventListener() for event-driven class changes.

Common event pattern

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

Useful state class names

  • is-active
  • is-open
  • is-hidden
  • is-loading
  • has-error

FAQ

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

Use addEventListener() on the button and call element.classList.add(), remove(), or toggle() inside the event handler.

What is the difference between className and classList?

className replaces the entire class string. classList lets you safely add, remove, toggle, and check individual classes.

Should I use onclick or addEventListener()?

For simple demos, either works. In real projects, addEventListener() is usually better because it keeps JavaScript separate from HTML.

Why is my class changing but nothing looks different?

Your CSS probably does not define any styles for that class, or another CSS rule is overriding it.

Can one element have multiple classes?

Yes. An element can have many classes, and classList helps manage them one at a time.

How do I remove one class without affecting others?

Use:

element.classList.remove("className");

How do I check if an element already has a class?

Use:

element.classList.contains("active");
Take Quiz

Mini Project

Description

Build a simple message box that the user can show and hide with a button. This demonstrates how JavaScript listens for a click event and changes an element's class to update its appearance.

Goal

Create a button that toggles a hidden message by adding and removing a CSS class.

Requirements

  • Create a button the user can click.
  • Create a message element that starts hidden.
  • Use JavaScript to listen for the button click.
  • Toggle a class on the message element.
  • Use CSS so the class actually changes visibility.
Take Quiz

Keep learning

Related questions

View more