Question
I have an HTML element that already has a class:
<div class="someclass">
...
</div>
How can I add another class to this div using JavaScript without replacing the existing class?
Short Answer
By the end of this page, you will understand how JavaScript adds CSS classes to existing HTML elements, why classList.add() is the preferred approach, how it differs from replacing className, and how this pattern is used in real web applications.
Concept
In JavaScript, HTML elements can have one or more CSS classes. These classes are stored in the element's class attribute.
For example:
<div class="someclass"></div>
This div currently has one class: someclass.
If you want to add another class, you usually should not overwrite the whole class attribute manually. Instead, use the DOM API designed for class management:
element.classList.add("newclass");
This matters because real applications often use classes to control:
- styling
- visibility
- animation
- validation state
- active or selected UI states
Using classList.add() is safer and clearer than rebuilding the class string yourself. It avoids accidentally removing existing classes and makes your code easier to read and maintain.
Mental Model
Think of an element's classes like stickers on a box.
className = "newclass"removes all old stickers and puts on one new sticker.classList.add("newclass")keeps the current stickers and adds one more.
So if a box already has a sticker labeled someclass, calling classList.add("highlight") means the box now has both stickers:
someclasshighlight
That is exactly what you want when adding behavior or styling without destroying what is already there.
Syntax and Examples
The most common syntax is:
element.classList.add("newclass");
Example 1: Add a class to a selected element
<div id="box" class="someclass">Hello</div>
<script>
const box = document.getElementById("box");
box.classList.add("active");
</script>
After this runs, the HTML behaves like this:
<div id="box" class="someclass active">Hello</div>
The original class stays, and the new class is added.
Example 2: Add multiple classes
box.classList.(, , );
Step by Step Execution
Consider this example:
<div id="message" class="note">Saved</div>
<script>
const message = document.getElementById("message");
message.classList.add("success");
</script>
Step by step:
- The browser reads the HTML.
- It creates a
divelement with:id=messageclass=note
document.getElementById("message")finds that element.- The variable
messagenow refers to thatdiv. message.classList.add("success")adds a new class.- The element now has two classes:
Real World Use Cases
Adding classes with JavaScript is very common in frontend development.
Common uses
- Show or hide UI elements
- Add a class like
hiddenoropen
- Add a class like
- Form validation
- Add
errororvalidafter checking input
- Add
- Active navigation links
- Add
activeto the current menu item
- Add
- Theme switching
- Add
dark-modeto the page or a container
- Add
- Animations
- Add
fade-inorshaketo trigger CSS animations
- Add
- Loading states
- Add
loadingwhile waiting for API data
- Add
Example: Show a menu
const menu = document.getElementById("menu");
menu..();
Real Codebase Usage
In real projects, developers usually combine classList.add() with DOM events, validation, and state changes.
Common patterns
Guard clauses
Check that the element exists before using it:
const modal = document.getElementById("modal");
if (!modal) return;
modal.classList.add("visible");
This prevents runtime errors when the element is missing.
Event-driven UI
const button = document.getElementById("toggleButton");
const panel = document.getElementById("panel");
button.addEventListener("click", () => {
panel.classList.add("open");
});
Validation feedback
function () {
input..();
}
Common Mistakes
1. Replacing all classes by mistake
Broken code:
element.className = "newclass";
Problem:
- This removes all existing classes.
Better:
element.classList.add("newclass");
2. Forgetting to select the element first
Broken code:
classList.add("active");
Problem:
classListbelongs to an element, not the whole document.
Better:
const element = document.getElementById("box");
element.classList.add("active");
3. Using className += incorrectly
Broken code:
Comparisons
| Approach | What it does | Keeps existing classes? | Recommended? |
|---|---|---|---|
element.classList.add("newclass") | Adds one or more classes | Yes | Yes |
element.className = "newclass" | Replaces all classes | No | Usually no |
element.className += " newclass" | Appends text to class string | Usually | Sometimes, but less ideal |
element.setAttribute("class", "newclass") | Replaces the whole class attribute | No | Usually no |
classList.add() vs
Cheat Sheet
Quick syntax
element.classList.add("newclass");
Select an element first
const element = document.getElementById("box");
Add one class
element.classList.add("active");
Add multiple classes
element.classList.add("active", "visible");
Check if a class exists
element.classList.contains("active");
Remove a class
element.classList.remove("active");
Toggle a class
FAQ
How do I add a class without removing existing classes in JavaScript?
Use:
element.classList.add("newclass");
This adds the new class and keeps the old ones.
What is the difference between classList.add() and className?
classList.add() adds a class safely. className sets the full class string, so it can replace all existing classes.
Can I add more than one class at once?
Yes:
element.classList.add("active", "visible");
What if the element already has that class?
classList.add() will not add it again in the normal way. The class remains present once.
Why is my code saying Cannot read properties of null?
Your element was probably not found yet. Make sure:
- the selector is correct
- the script runs after the element exists
Can I add a class to many elements at once?
Mini Project
Description
Build a simple notification box that changes appearance when a button is clicked. This demonstrates how JavaScript can add a new class to an element while keeping its existing class. It mirrors a common pattern used in alerts, banners, and UI messages.
Goal
Create a notification element that starts with one class and gains an additional class when the user clicks a button.
Requirements
- Create an HTML element with an existing class.
- Add a button that triggers the class change.
- Use JavaScript to add a new class without removing the old one.
- Style both classes in CSS so the visual change is obvious.
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.
Check If a Checkbox Is Checked with jQuery
Learn how to check whether a checkbox is checked in jQuery using the correct selector, with examples, mistakes, and practical patterns.
Convert HTML and CSS to PDF in PHP: Options, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose a practical approach for Linux web servers.