Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu August 29, 2022 . #class . #Element

How to add class to the body element using Javascript

Using the classList.add() method, we can add a class name to the body element. In this article, I will explain three (3️⃣) methods to add a class to the body using javascript.

Add a class to the body using add() method.

The built-in method add() allows to add one or more classes to a particular element.

Here is our first example.

Demo : add class to body using add() method
<html lang="en">
  <head>
    <style>
     .new-class{
      background-color: red;
     }
    </style>
  </head>
  <body>
   <script>
    document.body.classList.add('new-class')
   </script>
  </body>
</html>
Try it Yourself »
If the class already exists in the body element, the class will not be added twice to the body element.

Add multiple classes using add() method.

To add multiple classes to the body element using the add() method, Just pass the class names inside the add() method. e. g.

document.body.classList.add(
   'class1', 
   'class2', 
   'class3', 
   'class4'
   );

Output :-

<body class="class1 class2 class3 class4">
  ...... 
</body>

Remove class using remove() method.

To remove one or more classes from the body element, we will use the remove() method. e.g.

document.body.classList.remove(
   'class2', 
   'class4'
   )

Output :-

<body class="class1 class3">
  ...... 
</body>

Add class to the body using className property.

We can also use the className property instead of add() method to add a class to the body element. But the problem is that we cannot add more than one class to the body element at a time.

Demo: using the className property
<html lang="en">
  <head>
    <style>
     .new-class{
      background-color: red;
     }
    </style>
  </head>
  <body>
   <script>
    document.body.className="new-class"
   </script>
  </body>
</html>
Try it Yourself »

To add multiple classes, pass the class names separated by spaces to the className property. e.g.

document.body.className="new-class class2 ";

Output :-

<body class="new-class class2 ">
  ...... 
</body>

Add class using the setAttribute() method.

Use the setAttribute() method to add one or more classes to the body element. e.g.

document.body.setAttribute('class','new-class class2');

Output :-

<body class="new-class class2">
  ...... 
</body>

Conclusion

In this article, you have learned three methods to add a class to the body element using javascript.
  1. Using the add() method
  2. Using the className property
  3. Using the setAttribute ()method
save
listen
AI Answer
Write Your Answer
loading
back
View All