Checking Element has Specific CSS Class with Vanilla Javascript

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"
    console.log('Class is present');
    console.log('Class is not present');

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

See also  Smooth Scrolling with Pure CSS

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');
    console.log('All classes are not present');

Leave a Reply

Your email address will not be published. Required fields are marked *