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()
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").
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.(, () {
button = event..();
(!button) {
;
}
button..();
});
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.();
box..();
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") |
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
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:
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
Can You Style Half a Character in CSS? Text Effects with CSS and JavaScript
Learn how to style half of a character using CSS and JavaScript, including overlay techniques for dynamic text effects.
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.
Get the Selected Radio Button Value with jQuery
Learn how to find which radio button is selected in jQuery and get its value with simple examples and common mistakes.