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:
-
element.className- Replaces the entire class string.
- Simple, but easy to overwrite existing classes by mistake.
-
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.
classNamemeans 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.
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 {
: gray;
: white;
}
{
: green;
}
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:
- The browser loads the HTML.
- JavaScript runs
document.getElementById("card"). - The variable
cardnow refers to the<div>element. addEventListener("click", ...)tells the browser to wait for a click on that element.- When the user clicks the
<div>, the callback function runs. card.classList.toggle("highlight")checks whetherhighlightis already present.
Real World Use Cases
Changing classes with JavaScript is used everywhere in web development.
Common examples
- Navigation menus: add an
openclass when a mobile menu button is clicked - Form validation: add an
errorclass to invalid inputs - Tabs and accordions: add an
activeclass to the selected tab - Dark mode: toggle a
darkclass on thebody - Loading states: add a
loadingclass while waiting for an API response - Animations: add a class like
fade-into 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.();
});
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");
}
() {
input..();
}
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");
Comparisons
| Approach | What it does | Best for | Risk |
|---|---|---|---|
element.className = "active" | Replaces the full class string | Very simple cases | Can remove existing classes |
element.classList.add("active") | Adds one class | Most common updates | Low |
element.classList.remove("active") | Removes one class | Clearing a state | Low |
element.classList.toggle("active") | Adds or removes based on current state | On/off UI behavior | Can be confusing if you always want add |
element.classList.replace("old", "new") |
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
classListfor most class changes - Do not include
.in class names classNamereplaces the entire class stringtoggle()adds if missing, removes if present- returns multiple elements, so loop over them
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
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." ]
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.