javascript element classes

JavaScript Element Classes

In HTML, classes are attributes assigned to elements that allow developers to group elements for styling or scripting. A class can be thought of as a label that marks one or more elements, telling the browser or JavaScript what styles or behaviors apply to them. For example, if you want several buttons to look the same, you give them a shared class and then use CSS rules to style all those buttons consistently.

Classes matter because they are the main way to control how elements look through CSS, and they also help JavaScript identify and manipulate elements dynamically. Instead of hardcoding styles or changing inline styles directly, JavaScript can add, remove, or toggle classes to change the appearance or behavior of elements on the fly. This makes web pages interactive and adaptable.

This article will teach you how to use JavaScript’s classList API to add, update, remove, toggle, and check classes on HTML elements. You’ll see clear, copy-paste-ready examples that show how each method works in a practical way.

Adding Classes with classList.add()

To start, let’s learn how to add a class to an element using JavaScript. Imagine you have a colored box on the page, and you want to highlight it when the user clicks a button. The highlight effect is controlled by a CSS class named highlight.

Here is a complete example demonstrating this:

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Add Class Example</title>

  <style>

    #box {
      width: 150px;
      height: 150px;
      background-color: lightgray;
      margin-bottom: 10px;
      transition: border 0.3s ease;
    }

    .highlight {
      border: 5px solid orange;
    }

  </style>

</head>
<body>

  <div id="box"></div>
  <button id="btnHighlight">Highlight Box</button>

  <script>

    const box = document.getElementById('box');
    const button = document.getElementById('btnHighlight');

    button.addEventListener('click', () => {
      // Add the "highlight" class to the box element
      box.classList.add('highlight');
    });

  </script>

</body>
</html>

In this example, the box starts as a simple gray square. When the button is clicked, the JavaScript calls box.classList.add('highlight'). This adds the CSS class highlight to the box, causing it to show an orange border as defined in the CSS. Notice how adding classes allows you to change styles dynamically without altering inline styles directly.

You can also add multiple classes at once by passing several class names separated by commas, like element.classList.add('class1', 'class2').

Adding Class with element.className

You can use the className property to directly set an element’s class or classes. This approach assigns the full list of class names as a single string.

Here’s an example that sets a class on an element using .className:

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Set className Example</title>

  <style>

    .highlight {
      border: 2px solid orange;
      background-color: lightyellow;
    }

  </style>

</head>
<body>

  <div id="box">This box will be styled</div>
  <button id="setClassBtn">Set Class</button>

  <script>

    const box = document.getElementById('box');
    const button = document.getElementById('setClassBtn');

    button.addEventListener('click', () => {

      box.className = 'highlight'; // sets the class directly

    });

  </script>

</body>
</html>

In this example, clicking the button sets the className of the <div> to 'highlight'. This replaces any existing class names with exactly what you provide.

You can assign more than one class to an element by writing them as a space-separated string. This gives you full control over the exact class list you want the element to have.

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Set Multiple Classes</title>

  <style>

    .highlight {
      border: 2px solid orange;
    }

    .rounded {
      border-radius: 10px;
    }

  </style>

</head>
<body>

  <div id="box">Watch my style change</div>
  <button id="applyClasses">Apply Multiple Classes</button>

  <script>

    const box = document.getElementById('box');
    const button = document.getElementById('applyClasses');

    button.addEventListener('click', () => {

      box.className = 'highlight rounded'; // sets both classes

    });

  </script>

</body>
</html>

In this example, when the button is clicked, the highlight and rounded classes are both applied to the #box element. The string 'highlight rounded' is passed to className, and both classes are applied at once.

The difference between className and classList.add() is that className overwrites all existing classes, while classList.add() adds to the existing list. If you want more control over individual class names, use classList. If you want to reset the class entirely, className works just fine.

Updating Classes (Replacing One Class with Another)

When you want to change an element’s style by switching one class to another—such as changing a container’s theme from “day” to “night”—you can do this in two ways. The traditional method involves removing the old class and adding the new one separately. Alternatively, JavaScript provides a simpler method using classList.replace() to swap classes in one step.

Here is a basic example using remove() and add():

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Update Class Example</title>

  <style>

    .day {
      background-color: #fffacd;
      color: #000;
      padding: 20px;
      text-align: center;
    }

    .night {
      background-color: #2c3e50;
      color: #ecf0f1;
      padding: 20px;
      text-align: center;
    }

  </style>

</head>
<body>

  <div id="container" class="day">
    Good Morning!
  </div>
  <button id="btnToggleTheme">Switch to Night</button>

  <script>

    const container = document.getElementById('container');
    const button = document.getElementById('btnToggleTheme');

    button.addEventListener('click', () => {

      container.classList.remove('day');
      container.classList.add('night');

      container.textContent = 'Good Evening!';
      button.textContent = 'Switch to Day';

    });

  </script>

</body>
</html>

In this example, the container starts with the day class, which gives it a light background and dark text. Clicking the button removes day and adds the night class, changing the container to a dark theme. This method is straightforward but requires two separate steps.

Now, here is a cleaner way using classList.replace() to swap classes in one step and toggle back and forth:

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Update Classes with replace()</title>

  <style>

    .day {
      background-color: #f0e68c;
      color: #333;
      padding: 20px;
      text-align: center;
    }

    .night {
      background-color: #2c3e50;
      color: #ecf0f1;
      padding: 20px;
      text-align: center;
    }

  </style>

</head>
<body>

  <div id="themeBox" class="day">
    This is the Day theme
  </div>
  <button id="toggleThemeBtn">Toggle Theme</button>

  <script>
    const themeBox = document.getElementById('themeBox');
    const toggleBtn = document.getElementById('toggleThemeBtn');

    toggleBtn.addEventListener('click', () => {

      if (themeBox.classList.contains('day')) {

        themeBox.classList.replace('day', 'night');
        themeBox.textContent = 'This is the Night theme';

      } else {

        themeBox.classList.replace('night', 'day');
        themeBox.textContent = 'This is the Day theme';

      }

    });

  </script>

</body>
</html>

Here, classList.replace(oldClass, newClass) swaps the current class in a single step, simplifying the code. The button toggles the theme back and forth by checking which class is currently applied and replacing it accordingly.

This method reduces code complexity and improves readability, especially when switching between two states.

Removing Classes with classList.remove()

Removing a class is straightforward. Imagine you have a warning message styled with a warning class. When the user clicks a button, you want to remove that style, making the message look normal again.

Here is an demonstrating the classList.remove() method:

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Remove Class Example</title>

  <style>

    .warning {
      color: white;
      background-color: red;
      padding: 10px;
      border-radius: 4px;
      font-weight: bold;
    }

  </style>

</head>
<body>

  <p id="message" class="warning">Warning! This is a critical message.</p>
  <button id="btnClearWarning">Clear Warning</button>

  <script>

    const message = document.getElementById('message');
    const button = document.getElementById('btnClearWarning');

    button.addEventListener('click', () => {
      // Remove the "warning" class
      message.classList.remove('warning');
    });

  </script>

</body>
</html>

When the page loads, the paragraph has a bright red background and white text due to the warning class. Clicking the button removes this class, reverting the paragraph’s style to default. Using classList.remove() is a clean way to undo styles applied via classes.

Toggling Classes with classList.toggle()

Toggling is a very handy feature for switching a class on or off. For instance, toggling dark mode on a webpage is a common use case. If the class is present, toggle() removes it; if it’s missing, toggle() adds it.

Here’s an example demonstrating this:

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Toggle Class Example</title>

  <style>

    body {
      transition: background-color 0.3s ease, color 0.3s ease;
    }

    .dark {
      background-color: #121212;
      color: #e0e0e0;
    }

  </style>

</head>
<body>

  <button id="btnToggleDark">Toggle Dark Mode</button>

  <script>

    const body = document.body;
    const button = document.getElementById('btnToggleDark');

    button.addEventListener('click', () => {
      // Toggle the "dark" class on the body
      body.classList.toggle('dark');
    });

  </script>

</body>
</html>

Clicking the button switches the dark class on the <body> element on or off. When dark is added, the background and text colors change to create a dark mode effect. Clicking again removes the class, returning to the default light mode.

You can also pass a second boolean parameter to toggle(). This parameter lets you explicitly control whether the class should be added or removed, regardless of its current state. For example, calling classList.toggle('dark', true) forces the dark class to be added even if it’s already present or not, ensuring it is active. On the other hand, classList.toggle('dark', false) forces the class to be removed, making sure it is not present on the element. This gives you precise control over the element’s classes without needing to check their current state first.

Checking for a Class with classList.contains()

Sometimes you need to know if an element currently has a certain class. The classList.contains() method returns true if the class is present, or false if it is not.

Consider this example where a box may or may not have an active class, and a button checks its status:

<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="UTF-8" />
  <title>Check Class Example</title>

  <style>

    #box {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      margin-bottom: 10px;
    }

    .active {
      border: 3px solid green;
    }

  </style>

</head>
<body>

  <div id="box" class="active"></div>
  <button id="btnCheck">Is Box Active?</button>
  <p id="result"></p>

  <script>

    const box = document.getElementById('box');
    const button = document.getElementById('btnCheck');
    const result = document.getElementById('result');

    button.addEventListener('click', () => {

      // Check if "active" class exists on the box
      if (box.classList.contains('active')) {
        result.textContent = 'The box is active.';
      } else {
        result.textContent = 'The box is not active.';
      }

    });

  </script>

</body>
</html>

When you click the button, JavaScript checks if active is present on the box. It then updates the paragraph text accordingly. This method is helpful for conditional logic based on element state.

Summary Table: classList Methods

Here is a quick summary of the main classList methods you’ve learned:

MethodWhat it Does
add()Adds one or more classes to an element
remove()Removes one or more classes
toggle()Adds a class if missing, removes if present
contains()Returns true if the class exists, false otherwise
replace()Replaces one class with another

The replace() method allows you to swap one class for another in a single, simple step. It provides a convenient way to update an element’s classes without needing separate remove and add calls.

Conclusion

You now have a solid understanding of how to manipulate element classes using JavaScript’s classList API. By adding, removing, updating, toggling, and checking classes, you can change the look and behavior of elements dynamically. This lets you build interactive interfaces that respond to user actions, switch themes, highlight content, and more — all by controlling CSS classes through simple, readable JavaScript code.

References

Scroll to Top