Question

How to Add a Class to an HTML Element with JavaScript

htmljavascriptdom-manipulation

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:

  • someclass
  • highlight

That is exactly what you want when adding behavior or styling without destroying what is already there.

Take Quiz

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.add("active", "visible", "rounded");

Example 3: Compare with a riskier approach

You may see this:

box.className += " active";

This can work, but it is less safe because:

  • you must remember the leading space
  • you can accidentally create duplicate classes
  • it is harder to read and maintain

For beginners, classList.add() is the best choice.

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:

  1. The browser reads the HTML.
  2. It creates a div element with:
    • id = message
    • class = note
  3. document.getElementById("message") finds that element.
  4. The variable message now refers to that div.
  5. message.classList.add("success") adds a new class.
  6. The element now has two classes:
<div id="message" class="note success">Saved</div>

The existing class is preserved, which is the key idea.

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 hidden or open
  • Form validation
    • Add error or valid after checking input
  • Active navigation links
    • Add active to the current menu item
  • Theme switching
    • Add dark-mode to the page or a container
  • Animations
    • Add fade-in or shake to trigger CSS animations
  • Loading states
    • Add loading while waiting for API data

Example: Show a menu

const menu = document.getElementById("menu");
menu.classList.add("open");

Example: Mark invalid input

const emailInput = document.getElementById("email");
emailInput.classList.add("error");
Take Quiz

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 showError(input) {
  input.classList.add("error");
}

State-based styling

Developers often add classes based on application state instead of manually changing many style properties:

if (isLoading) {
  container.classList.add("loading");
}

This keeps JavaScript focused on logic and CSS focused on presentation.

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:

  • classList belongs to an element, not the whole document.

Better:

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

3. Using className += incorrectly

Broken code:

element.className += "active";

Problem:

  • This produces someclassactive instead of someclass active.

Safer version:

element.classList.add("active");

4. Running JavaScript before the element exists

Broken code:

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

Problem:

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

Better approaches:

  • place the script at the end of the body
  • or wait for the DOM to load

Example:

document.addEventListener("DOMContentLoaded", () => {
  const element = document.getElementById("box");
  element.classList.add("active");
});

5. Adding a class to multiple elements incorrectly

If you use querySelectorAll(), you get a collection, not a single element.

Broken code:

const items = document.querySelectorAll(".item");
items.classList.add("active");

Better:

const items = document.querySelectorAll(".item");
items.forEach(item => item.classList.add("active"));

Comparisons

ApproachWhat it doesKeeps existing classes?Recommended?
element.classList.add("newclass")Adds one or more classesYesYes
element.className = "newclass"Replaces all classesNoUsually no
element.className += " newclass"Appends text to class stringUsuallySometimes, but less ideal
element.setAttribute("class", "newclass")Replaces the whole class attributeNoUsually no

classList.add() vs className

  • Use classList.add() when you want to manage classes safely.
  • Use className only when you intentionally want to replace the full class string.

Related methods on classList

MethodPurpose
add()Add a class
remove()Remove a class
toggle()Add if missing, remove if present
contains()Check whether a class exists
Take Quiz

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

element.classList.toggle("active");

Important rule

  • classList.add() keeps existing classes.
  • className = "..." replaces existing classes.

Common safe pattern

const element = document.getElementById("box");
if (element) {
  element.classList.add("active");
}

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?

Yes, loop through them:

document.querySelectorAll(".item").forEach(item => {
  item.classList.add("active");
});

Should I use JavaScript to change styles directly instead of classes?

Usually, classes are better. They keep styling in CSS and logic in JavaScript.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more