How to Add a Class to an Element in JavaScript

In JavaScript, adding a CSS class to an element is a common task when you want to change the appearance or behavior of that element dynamically. This is especially useful for interactive web pages where styles change based on user actions. In this post, we'll explore how to add a class to an element in JavaScript.

Table of Contents

  1. Using classList.add()
  2. Adding Multiple Classes
  3. Checking if an Element Has a Class Before Adding
  4. Using className Property (Legacy Method)
  5. Conclusion

1. Using classList.add()

The classList.add() method is the most straightforward and modern way to add a class to an element in JavaScript. This method ensures that the class is added only once, even if it’s already present.

Example:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .highlight {
      color: white;
      background-color: red;
      padding: 10px;
    }
  </style>
  <title>Add Class Example</title>
</head>
<body>
  <h1 id="heading">Hello, World!</h1>
  <button onclick="addHighlight()">Add Highlight</button>
  <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

function addHighlight() {
  const heading = document.getElementById("heading");
  heading.classList.add("highlight");
}

Explanation:

  • document.getElementById("heading") selects the <h1> element by its ID "heading".
  • classList.add("highlight") adds the "highlight" class to the element, applying the styles defined in the CSS.

Output:

Clicking the "Add Highlight" button will apply the .highlight class, changing the appearance of the <h1> element based on the CSS rules.

2. Adding Multiple Classes

You can add multiple classes to an element by passing multiple class names as arguments to classList.add().

Example:

function addMultipleClasses() {
  const heading = document.getElementById("heading");
  heading.classList.add("highlight", "bold-text", "extra-padding");
}

Explanation:

  • You can add several classes at once by passing them as separate arguments to classList.add(). In this example, the element will receive three new classes: "highlight", "bold-text", and "extra-padding".

3. Checking if an Element Has a Class Before Adding

If you want to ensure a class is not added twice, even though classList.add() already prevents duplicates, you can use classList.contains() to check if the element already has the class.

Example:

function addHighlightIfNotExists() {
  const heading = document.getElementById("heading");
  
  if (!heading.classList.contains("highlight")) {
    heading.classList.add("highlight");
  }
}

Explanation:

  • classList.contains("highlight") checks if the element already has the "highlight" class. If it doesn’t, the class is added.

4. Using className Property (Legacy Method)

Before classList was introduced, the common way to add a class was by manipulating the className property. This method involves manually setting the entire class list as a string, which can overwrite existing classes if not done carefully.

Example:

function addHighlightLegacy() {
  const heading = document.getElementById("heading");
  heading.className += " highlight";  // Adds a new class, ensuring there’s a space before the new class name
}

Explanation:

  • The className property returns or sets the full class attribute of an element as a string. By appending " highlight" to className, we add the "highlight" class. You must add a space before the new class to avoid merging it with existing classes.

Caution:

  • Using className to modify the class list can lead to problems if you unintentionally overwrite other existing classes.

5. Conclusion

Adding a class to an element in JavaScript is easy and can be done using the modern classList.add() method, which is the recommended approach. This method ensures that classes are added efficiently and safely without duplicating existing classes. You can also check if a class exists before adding it, or add multiple classes at once.

Key Points:

  • classList.add(): The modern and efficient way to add one or more classes to an element.
  • Multiple Classes: You can add multiple classes using classList.add("class1", "class2").
  • classList.contains(): Use this method to check if a class is already present.
  • className: An older method that should be avoided unless compatibility with very old browsers is needed.

Comments