How to Add Multiple Classes to Element in JavaScript

JavaScript stands as a versatile and robust programming language favored by software developers and web designers alike. It boasts a plethora of applications and is instrumental in creating diverse web applications and websites, including mobile applications. In this article, we will delve into the techniques for incorporating multiple classes using JavaScript, while also discussing best practices, benefits, and guidance for troubleshooting.

How to add multiple classes with JavaScript?

In JavaScript, incorporating multiple classes is straightforward. There are three primary methods available for this purpose: classList.add, .className, and setAttribute. These methods allow you to add one or more class names to a particular element within the DOM. Additionally, the classList.remove method is available to eliminate classes from the DOM. Finally, the classList.toggle method can be utilized to either activate or deactivate a class for a designated element.

It is important to note that the methods classList.add and classList.remove can take multiple class names as arguments. This capability is advantageous for adding or removing several classes simultaneously, which can be beneficial for efficiently managing various classes on a single element. Additionally, the classList.toggle method also supports multiple class names as parameters. This means that you can enable or disable several classes at once.

In most of these scenarios, we will encounter illustrations of altering one or several HTML elements by applying custom CSS properties triggered by user interactions. These dynamic modifications can be accomplished using JavaScript. Let’s delve into the specifics of how to append a class in JavaScript.

Utilizing the .className Property

The .className attribute represents the most straightforward and conventional approach for managing classes. It allows for the addition of a class in JavaScript while also enabling the retrieval of the names of any classes that have already been assigned to an element. Additionally, the .className attribute can be utilized to assign multiple classes to a single element.

Syntax:

Example

el.className = "new-class";

Property Value:

newClass: It is essential to enclose this section within double quotation marks to specify the new class name. Multiple class names can be added by inserting a space following each new class name.

Syntax for multiple classes:

Example

el.className = "class1 class2 class3"

Return Value:

The value returned by the .className property is a string that denotes one or more class names.

Example

<!DOCTYPE html>
<html>
<head>
  <title>Example in JavaScript to add class name</title>
  <style>
    .addingCSS {
      color: green;
      font-size: 20px;
    }
  </style>
</head>
<body style="text-align:left;">
  <h1 style="color:red;">
    Example for .className to add class
  </h1>
  <p id="p">By pressing this button it will add CSS class</p>
  <button onclick="addingClass()"> Click here to add class </button>
  <!-- Script to add class name -->
  <script>
    function addingClass() {
      var v = document.getElementById("p");
      v.className = "addingCSS"; // Using el.className = "new-className"
    }
  </script>
</body>
</html>

Output

Upon clicking the button, it will appear as a green sentence as illustrated below:

In the code provided above, a basic HTML structure is utilized that features a header, a text paragraph, and a button equipped with an onclick event that triggers when the button is pressed. The accompanying JavaScript contains a function named addingClass. This function attempts to locate the paragraph element by its ID. Once the element is successfully identified, a class name is appended to it through the use of the .className property.

Employing the .add method in ClassList

An additional approach available in JavaScript for assigning a class is through the .add method. Alternatively, the .classList property can be utilized to associate a class with an element. This property also allows for the inclusion of multiple classes to a single element.

Syntax:

Example

el.classList.add("new-className");

Property Value:

The .classList property is immutable, yet it provides an .add method that allows for the inclusion of classes in JavaScript. This .add method linked to .classList accepts the name or multiple names of the class as a string enclosed in double quotes.

Return Type:

The .classList method returns a DOMTokenList, which contains a collection of tokens that are separated by spaces.

Let us illustrate this with an example.

Example

<!DOCTYPE html>
<html>
<head>
  <title>Example in JavaScript to add class name</title>
  <style>
    body{
      display: flex;
      flex-direction: column;
      justify-content: left;
      align-items: left;
    }
    .addCSS {
      background-color: grey;
      width: 100px;
      height: 100px;
      color: opaque;
    }
    button{
      margin-top: 20px;
      width: 200px;
    }
  </style>
</head>
<body>
  <h1 style="color:blue;">
    Using .classList.add() to add class in JavaScript
  </h1>
  <div class="p">Added class appears here</div>
  <button onclick="addClass()"> AddClass </button>
  <!-- Script to add class name -->
  <script>
    function addClass() {
      var v = document.querySelector(".p");
      v.classList.add("addCSS"); // Using el.classList.add()
    }
  </script>
</body>
</html>

Output

After clicking AddClass button:

In the example provided, a basic HTML structure is employed, similar to what has been demonstrated in earlier instances. It features a button that activates an on-click event; when this button is clicked, it invokes a JavaScript function. Within the JavaScript portion, there exists a function named addClass. This particular function utilizes querySelector to identify the paragraph class. After the element has been selected, a class name is appended by utilizing .classList.add.

Add class using the setAttribute method

The setAttribute function, utilized for adding a class, designates a value to an element's attribute. In cases where the attribute is already present, this method will modify its existing value; if not, it will generate a new attribute and assign the specified value to it.

Syntax:

Example

el.setAttribute(name, value);

The setAttribute function requires two arguments. It comprises the name of the attribute that is to be established and the corresponding value that is assigned to that specific attribute.

Let's recreate the output as in .add here.

Example

<!DOCTYPE html>
<html>
<style>
.set {
  color: blue;
}
</style>
<body>
<h1 id="myMain">One Element Object</h1>
<h2>The setAttribute() Method</h2>
<p>Click here "Add Class" to add a class attribute to the element:</p>
<button onclick="myFunction()">Add Class</button>
<script>
function myFunction() {
  document.getElementById("myMain").setAttribute("class", "set"); 
}
</script>
</body>
</html>

Output

After clicking Add class button:

In the aforementioned scenario, we are utilizing the same framework that was previously mentioned. The sole distinction in the current code is found within the JavaScript function. Here, we have substituted the use of .classList.add with the setAttribute method, which assigns the addCSS class to the div HTML element through JavaScript. It is recommended to employ this compiler for compiling your code.

Toggle Method

As mentioned earlier, the .classList method includes an additional capability that allows users to add a class through JavaScript if it has not yet been applied. Conversely, if the class is already present, the method will remove it instead.

Syntax:

Example

el.classList.toggle("new-className");
Example

<!DOCTYPE html>
<html>
<style>
.myStyle {
  background-color: orange;
  padding: 26px;
}
</style>
<body>
<h3>Example for toggle Object</h3>
<h4>The toggle() Method in JavaScript</h4>
<button onclick="myFunction()">Toggle</button>
<p>Click "Toggle" button to toggle "myStyle" on and off.</p>
<div id="myDIV">
<p>I am hidden toggle object.</p>
</div>
<script>
function myFunction() {
  document.getElementById("myDIV").classList.toggle("myStyle");
}
</script>
</body>
</html>

Output

When we click on the Toggle button:

The .classList interface includes a remarkable method known as .toggle. This method facilitates the dynamic assignment of a class when it is not already applied. On the other hand, if the class is present, the .toggle method will eliminate it.

Advantages of incorporating multiple classes with JavaScript

Integrating multiple classes into your code offers numerous advantages. It grants developers significantly enhanced control over the styling of elements, allowing for rapid modifications to the visual design of any page without the need to alter the underlying code. Moreover, utilizing various classes facilitates the creation of multiple iterations of a web page, all derived from the same foundational code, merely by adjusting class attributes.

Moreover, it guarantees that the code remains organized and comprehensible. Given that the styling and functionality of the components are distinctly categorized into separate classes, identifying any errors becomes a straightforward task. Additionally, this methodology minimizes the overall number of code lines, as a single class can be utilized across various elements, facilitating their reuse for other components within the project.

Conclusion

This article focuses on the process of appending multiple classes via JavaScript, accompanied by recommended practices and illustrative examples. By adhering to the steps outlined below, it is possible to incorporate various classes into an element within a web page or application:

Keep in mind that when you assign multiple classes to a single element, it is crucial to adhere to the correct formatting and syntax. Additionally, it is vital to identify any potential conflicts that might arise from the interplay of different classes. Lastly, it is essential to thoroughly test the code to ensure that the classes function as intended.

Input Required

This code uses input(). Please provide values below: