Check if Body has a specific Class using JavaScript


Borislav Hadzhiev

Sun Jan 02 20222 min read

Check if Body has a specific Class using JavaScript #

Use the classList.contains() method to check if the body element has a specific class, e.g. document.body.classList.contains('my-class'). The method returns a boolean value - true if the element's class list contains the class and false otherwise.

Here is the HTML for the examples in this article.

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

And here is the related JavaScript code.

const bodyHasClass = document.body.classList.contains( 'bg-salmon' ); if (bodyHasClass) { console.log('โœ… body element has class'); } else { console.log('โ›”๏ธ body element does not have class'); }

The body property on the document object gives us access to the body element.

We used the classList.contains method to check if the body element has a specific class.

The method returns true if the provided class is contained in the element's class list and false otherwise.

If you need to add or remove a class from the body element, you can use the classList.add() and classList.remove() methods.

// โœ… Add classes to <body> element document.body.classList.add('first-class', 'second-class'); // โœ… Remove classes from <body> element document.body.classList.remove('bg-salmon', 'third-class');

The classList.add method adds one or more classes to the element.

If any of the provided classes already exists on the element, the classes will not get added a second time.

The classList.remove method removes one or more classes from the element.

If any of the classes are not present on the element, the remove() method does not throw an error, it simply ignores the class.

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