Native Class Operations with the HTML5 classList

With the help of the classList API, we can directly manage our HTML classes from JavaScript like we did in jQuery.

The classList property is supported for a long time in all modern browsers. The property is available at all DOM node.

Before the classList, the JS class management was a pain in the back. You have to use quite a lot helper function to achieve some simple result. The property has five methods which are the followings: add(), contains(), item(), remove(), toggle().

You can also check the object length with the standard length property.

Add Class

When you want to add a new class to a node object you can use the classList object add() method:


You can also give multiple values separated by space.

Remove Class

For removing use the remove() method:


For more removes separate the items with space.

Toggle Class

The toggle() method saves us from some additional check. It eliminates the value if the node has and add the value if the node doesn’t have.


Check Class

If you like only to check if a node has a particular class, then you can use the contains() method which is giving back a boolean value.

if(document.querySelector.classList.contains('post')) {
    console.log('Class found...');
} else {
    console.log('Class not found...');

Nth Class

The item() method came in handy when you like to get one item by order number.

document.querySelector('.main').classList.item(1); // .main


With the classList, the JavaScript get back one more field from jQuery. This object combined with the querySelector(All) method can be powerful alone. Of course, you have to learn the difference between the node object and the jQuery object, but after that, you can easily use plain JS in your next project!