Borislav Hadzhiev
Fri Dec 31 2021·2 min read
Photo by Rosan Harmens
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.
<!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.
// ✅ 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.
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.
document.body.classList.remove( 'salmon', 'second-class', 'third-class' );
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.
// ✅ 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