Checking Element has Specific CSS Class with Vanilla Javascript

javascript
Published on April 2, 2019

Similar to the jQuery hasClass method, there exists a native Javascript method that tells whether the DOM element contains the specified CSS class or not.

This is done with the contains method of the classList object. The classList object is a property of the DOM element containing a list of its class attributes.

// check if #target-element contains class "current-post"
if(document.querySelector("#target-element").classList.contains('current-post'))
    console.log('Class is present');
else
    console.log('Class is not present');

The contains method will return a true if the class is present, and false otherwise.

Checking for multiple classes ? The contains method accepts just a single classname as its parameter. To check if multiple classes are present in the element, you will need to call the contains method multiple times.

// check if #target-element contains classes "post" & "news"
if(document.querySelector("#target-element").classList.contains('post') && document.querySelector("#target-element").classList.contains('news'))
    console.log('All classes are present');
else
    console.log('All classes are not present');
In this Tutorial