Add a class to the Body element using JavaScript

avatar

Borislav Hadzhiev

Wed Dec 29 20212 min read

banner

Photo by Jad Limcaco

Add a class to the Body element using JavaScript #

To add a class to the body element, call the classList.add method on the body object, e.g. document.body.classList.add('my-class'). The add() method adds one or more classes to the list, omitting any that are already present.

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');

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 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';
The code snippet above adds the class twice, because there isn't any check in place to only add the class if it's not 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. 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'); });

We added a click event listener to the button element.

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee