Remove a class from the Body element using JavaScript

avatar

Borislav Hadzhiev

Fri Dec 31 20212 min read

banner

Photo by Rosan Harmens

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 object, e.g. document.body.classList.remove('my-class'). The remove() method removes one or more classes from the element's class list.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body class="salmon"> <div>Box Content here</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// ✅ Remove class from Body document.body.classList.remove('salmon'); // ✅ Add class to Body // document.body.classList.add('my-class');

We can access the body element directly on the document object.

We used the classList.remove method to remove the salmon class from the body element.

The classList.remove() method can be used to remove classes from any type of element, not just the body.

Note that you can pass as many classes as necessary to the remove() method.

index.js
document.body.classList.remove( 'salmon', 'second-class', 'third-class' );
If any of the classes is not present on the element, the remove() method ignores the class and does not throw an error.

Conversely, you can add a class to the body element, by calling the classList.add() method on the element.

index.js
// ✅ Add class to Body document.body.classList.add( 'first-class', 'second-class', 'third-class' );

If any of the classes passed to the add() method is already present on the body element, it will be omitted.

When using the classList.remove() and classList.add() methods, you don't have to worry about:

  • getting errors when removing a class that is not present on the element

  • adding the same class multiple times to the same element

Use the search field on my Home Page to filter through my more than 1,000 articles.