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.
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
highlightclass on thediv. - 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
- JavaScript finds the button using
document.getElementById("btn"). - JavaScript finds the message element using
document.getElementById("message"). - The code attaches a click event listener to the button.
- At this point, the
divhas the classhidden, so it is not visible. - When the user clicks the button, the function inside
addEventListenerruns. message.classList.toggle("hidden")checks whetherhiddenexists.- Since
hiddenexists, JavaScript removes it. - The CSS rule no longer applies, so the message becomes visible.
- If the button is clicked again,
toggle()addshiddenback. - 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
errorclass when validation fails - adding a
successclass after valid input - highlighting required fields
App state changes
- toggling dark mode
- showing loading states with a
loadingclass - disabling or dimming elements visually
- changing status indicators like
onlineandoffline
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.
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-openis-activeis-hiddenhas-erroris-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
| Approach | What it does | Keeps existing classes? | Best use |
|---|---|---|---|
element.className = "active" | Replaces the full class string | No | When you want to fully overwrite classes |
element.classList.add("active") | Adds one class | Yes | Most common way to enable a style |
element.classList.remove("active") | Removes one class | Yes | Removing a state or style |
element.classList.toggle("active") | Adds or removes a class automatically | Yes | Click-based UI toggles |
element.classList.replace("a", "b") | Swaps one class for another | Yes | Moving between known states |
onclick vs addEventListener
| Method | Pros | Cons |
|---|---|---|
onclick attribute in HTML | Simple for tiny demos | Mixes HTML and JavaScript, harder to scale |
addEventListener() | Cleaner, reusable, supports multiple listeners | Slightly more code |
In modern JavaScript, addEventListener() is usually the better choice.
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
classListfor most cases. - Do not include
.in class names when using JavaScript methods. classNameoverwrites 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-activeis-openis-hiddenis-loadinghas-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");
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.
Keep learning
Related questions
Add a Favicon to a Static HTML Page
Learn how to add a favicon to static HTML pages, use correct paths and icon formats, and troubleshoot browser caching and local-file issues.
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
Apply CSS !important with jQuery .css()
Learn why jQuery .css() cannot set !important and how to use CSSStyleDeclaration.setProperty() to apply inline important styles safely.