Add a class to the Body element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Add a class to the Body element using JavaScript #

Use the classList.add() method to add a class to the body element, e.g. document.body.classList.add('my-class'). The classList.add() method will add the supplied class to the body element.

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> <div>Some content here</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
document.body.classList.add('salmon');

add class to body

We used the add() method to add a class on the body object.

We can access the body element on the document object.

If the class is already present on the body element, it won't get added twice.

You can pass as many classes to the add() method as necessary.

index.js
document.body.classList.add( 'salmon', 'second-class', 'third-class' );

Similarly, if you need to remove one or more classes, you can use the classList.remove() method.

index.js
// ✅ Add classes document.body.classList.add( 'salmon', 'second-class', 'third-class' ); // ✅ Remove classes document.body.classList.remove( 'salmon', 'third-class' );

You might have seen examples online that reassign the className property on the body element.

index.js
document.body.className += ' salmon';

This approach works, however when using it we don't take advantage of some of the built-in functionality the classList.add() method provides.

index.js
document.body.className += ' salmon'; document.body.className += ' salmon';

add class to body using classname

The code snippet above adds the class twice because there isn't any check in place to only add the class if it isn't already present on the element.

This would lead to very confusing behavior if you have to toggle a class or remove it.

You can also add a class to the body element when an event occurs, e.g. when a button is clicked.

Here is the HTML for the next example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div>Some content here</div> <button id="btn">Click me</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) { document.body.classList.add('salmon'); });

add class to body when event occurs

We added a click event listener to the button element.

Each time the button is clicked, the onClick function is invoked.

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