How to Remove a Class from the Body Element using JavaScript

Last updated on November 10, 2022
How to Remove a Class from the Body Element using JavaScript

To remove a class from the body element, call the classList.remove() method on the body element, e.g, document.body.classList.remove('the-class)'.

Here is some sample HTML:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body class="class-1 class-2">
    <div>This is a div element.</div>

    <script src="index.js"></script>
  </body>
</html>

Here's how we can remove the class class-1 from the body using JavaScript:

index.js

document.body.classList.remove('class-1');

We use the body property of the document to access the HTMLElement object that represents the document body.

The classList property returns a DOMTokenList object that represents the list of classes an element has.

The remove() method of the classList property takes a list of classes and removes them from an element.

After removing class-1, the document markup will look like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body class="class-2">
    <div>This is a div element.</div>

    <script src="index.js"></script>
  </body>
</html>

We can pass multiple arguments to the remove() method to remove more than one class from the body. For example, we can remove both class-1 and class-2 from the body using a single statement:

index.js

document.body.classList.remove('class-1', 'class-2');

This will be the resulting document markup:

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body>
    <div>This is a div element.</div>

    <script src="index.js"></script>
  </body>
</html>

If we pass a class that the element does not have, remove() ignores the class and does not throw an error.

Add class to body with JavaScript

To add a class to the body element instead, we can use the classList.add() method of the body object.

index.js

document.body.classList.add('class-3', 'class-4');

The add() method of the classList property takes a list of class names and adds them to an element.

This will be the resulting HTML after adding the two classes:

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Beauty Tutorial</title>
  </head>
  <body class="class-1 class-2 class-3 class-4">
    <div>This is a div element.</div>

    <script src="index.js"></script>
  </body>
</html>

add() prevents the same class from being added to an element multiple times, so a specified class is ignored if the element already has it.

See also