Check if Body has a specific Class using JavaScript

avatar

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.

index.html
<!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.

index.js
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.

index.js
// ✅ 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.
Use the search field on my Home Page to filter through my more than 1,000 articles.