Checking, Adding and Removing classNames from an Element is really important, and really easy too. Even if you’re just using Plain, Vanilla JavaScript, because you really don’t need a library to just handle a single attribute. So I will show you 3 simple ways how to just play with elements classes.

ClassList: The modern Way

The most modern way, which I personally don’t use, is the “new” classList property. It is available since 8, 3.6, 11.5, 5.1 and 10. As you may see “new” isn’t always meant to be “new”. This property has 6 different methods, but which arn’t supported in all browsers mentioned before.

The most confused browser is the Internet Explorer, which just doesn’t want to be cool. It doesn’t support multiple Strings on the .add() and .remove() methods, and the .toggle() and .replace() functions are totally unknown to him. Now you just can use a Polyfill like this one on the MDN WebDocs, which adds partial support for IE 6 – 8 and full Support for IE 9+!

Show ClassList Methods
.add(String [, String [, ...]])
The add method just adds a single or multiple class names to the respective element. The class get be ignored, if it does already exist.
Please Note: The Internet Explorer doesn’t support multiple strings at all, the other browsers only from a specific version: 24, 26, 15, 7 and 12.

.remove(String [, String [, ...]])
The remove Method just removes a single or multiple class names to the respective element. A class name that doesn’t exist doesn’t throw any error.
Please Note: The Internet Explorer doesn’t support multiple strings at all, the other browsers only from a specific version: 24, 26, 15, 7 and 12.

.item(Number)
This method just returns the class name, according to the respective index collection.

.toggle(String [, force])
The toggle method “adds” a class name if it doesn’t exist (and returns true) or removes it (and returns false). The second parameter is a Boolean value that forces the class to be added or removed, regardless of whether or not it already existed.
Please Note: The Internet Explorer doesn’t support multiple strings at all, the other browsers only from a specific version: 24, 24, 15, 7 and 12.

.contains(String)
This method just checks if the specific class name does already exist (true) or not (false).

.replace(oldClass, newClass)
The replace method replaces the “oldClass” with the “newClass”, if the oldClass does exist.
Please Note: This method is really pretty new and the only known browser who supports this are 61 and 49.

RegExp: The Regular Way

My favourite way, because it has a deeper and non-confusing browser support, is just RegExp. Check, Add, Replace and (if desired) also Toggle class names just with some regular expressions. It’s easy to implement, and easy to use too.

A really simple Solution

This is the original version, which I use in my scripts (except the .toggleClass method)! It is supported in all known browsers including 9+, but if you need something deeper just replace the .trim() functions with the following line (Source): .replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')!

It is “really simple”, I mean it is so simple it doesn’t even check if the first parameter el is an element at all. The functions are already satisfied if el has a “className” property. It also doesn’t check if the second parameter is a String (Potential Error), or contains multiple space-separated class names. However, I use this snippet outside of the users environment, therefore I also know which arguments pass this functions.

Show Code Snippet
var tool = {
    hasClass: function(el, name){
        return (new RegExp("(|\s+)" + name + "(\s+|)")).test(el.className || "");
    },
    addClass: function(el, name){
        if(!(new RegExp("(|\s+)" + name + "(\s+|)")).test(el.className || name)){
            el.className = (el.className.trim() + " " + name.trim()).trim();
        }
        return el;
    },
    removeClass: function(el, name){
        var regex = new RegExp("(|\s+)(" + name + ")(\s+|)");
        if(regex.test(el.className || "")){
            el.className = (el.className.replace(regex, "$1$3")).trim();
        }
        return el;
    },
    toggleClass: function(el, name){
        var regex = new RegExp("(|\s+)(" + name + ")(\s+|)");
        if(regex.test(el.className || "")){
            el.className = (el.className.replace(regex, "$1$3")).trim();
        } else if(!regex.test(el.className || name)){
            el.className = (el.className.trim() + " " + name.trim()).trim();
        }
        return el;
    }
};

A more complex Solution

My Version above can also be extended, if you want to check, add, remove and toggle multiple class names at once, for example. The “more complex” solution (now also documented), checks the passed arguments and supports multiple class names and partially adds also some additional settings. AND You can easily adapt this to your needs, of course!

Show Code Snippet
var tool = {
    /*
     |  CHECK IF ONE / ALL CLASS NAMES EXISTS
     |  
     |  @param  Element An element object.
     |  @param  String  A (space-separated) String with all requried class names,
     |          Array   An Array Instance with all required class names.
     |  @param  Bool    Set this to true if just ONE class name need to be exist,
     |                  Otherwise this function returns only true if all class names does exist!
     |
     |  @return Bool    Returns true if one (once = true) or all class names does exist and false if not!
     */
    hasClass: function(el, classes, once){
        if(typeof(classes) == "string"){
            classes = classes.split(" ");
        }
        if(!(el instanceof Element) || !(classes instanceof Array)){
            return false;
        }
        
        // Loop Class Names
        var _check = 0;
        for(var l = classes.length, i = 0; i < l; i++){
            if((new RegExp("(|\s+)" + classes[i] + "(\s+|)")).test(el.className)){
                if(once){
                    return true;
                }
                _check++;
            }
        }
        return (_check == classes.length);
    },
    
    /*
     |  ADD ONE OR MORE CLASS NAMES
     |  
     |  @param  Element An element object.
     |  @param  String  A (space-separated) String with all requried class names,
     |          Array   An Array Instance with all required class names.
     |  @param  Bool    Set this ti true to add the class name also if it deos already exist!
     |
     |  @return String  Returns the current class names string.
     */
    addClass: function(el, classes, force){
        if(typeof(classes) == "string"){
            classes = classes.split(" ");
        }
        if(!(el instanceof Element) || !(classes instanceof Array)){
            return false;
        }
        
        // Loop Class Names
        for(var l = classes.length, i = 0; i < l; i++){
            if(force === true || !(new RegExp("(|\s+)" + classes[i] + "(\s+|)")).test(el.className)){
                el.className += " " + classes[i];
            }
        }
        el.className = el.className.trim();
        return el.className;
    },
    
    /*
     |  REMOVE ONE OR MORE CLASS NAMES
     |  
     |  @param  Element An element object.
     |  @param  String  A (space-separated) String with all requried class names,
     |          Array   An Array Instance with all required class names.
     |
     |  @return String  Returns the current class names string.
     */
    removeClass: function(el, classes){
        if(typeof(classes) == "string"){
            classes = classes.split(" ");
        }
        if(!(el instanceof Element) || !(classes instanceof Array)){
            return false;
        }
        
        // Loop Class Names
        for(var regex, l = classes.length, i = 0; i < l; i++){
            regex = new RegExp("(|\s+)(" + classes[i] + ")(\s+|)");
            if(regex.test(el.className)){
                el.className = (el.className.replace(regex, "$1$3")).trim();
                el.className = el.className.replace(/  /g, " ");
            }
        }
        return el.className;
    },
    
    /*
     |  TOGGLE ONE OR MORE CLASS NAMES
     |  
     |  @param  Element An element object.
     |  @param  String  A (space-separated) String with all requried class names,
     |          Array   An Array Instance with all required class names.
     |
     |  @return String  Returns the current class names string.
     */
    toggleClass: function(el, classes){
        if(typeof(classes) == "string"){
            classes = classes.split(" ");
        }
        if(!(el instanceof Element) || !(classes instanceof Array)){
            return false;
        }
        
        // Loop Class Names
        for(var regex, l = classes.length, i = 0; i < l; i++){
            regex = new RegExp("(|\s+)(" + classes[i] + ")(\s+|)");
            if(regex.test(el.className)){
                el.className  = (el.className.replace(regex, "$1$3")).trim();
            } else {
                el.className += " " + classes[i];
            }
        }
        return el.className;
    }
};

ClassName: The Simple Way

The second way above uses the className property of the Element object. If you're working on just a small WebApplication, where your know the class names, then you may don't need RegExp. In this case you can directly interact with the respective property and check, add, replace your class names directly.

Show Code Snippet
var element = document.getElementById("web-scripts");

/*
 |  The className property contains all class names (space separated!)
 */
if(element.className != "active"){
    /*
     |  Which means, when you assign a new value all previously gets "removed"!
     */
    element.className = "active";
}

/*
 |  If you want to keep the classNames just use the += operator.
 */
if(element.className == "active"){
    element.className += " second-class";
}

/*
 |  But don't forget, that you've added it AND in which order!
 */
if(element.className == "active"){
    console.log(" This will not work! ");
} else if(element.className == "active second-class"){
    console.log(" This will work! ");
}

/*
 |  Just Play with this property like with any other String.
 */
if(element.className.indexOf("active") >= 0){
    element.className = element.className.replace("active", "");
}

Simple Enough?

You know that you don't need a Selector Engine, and now you should've learned that you can control your class names on your own. You don't need a fat library to just control such an easy thing, even if the library may has some additional className depending functions. It's "just a space-separated" string, handle it like any other string too (or use the classList property)!

But please don't get me wrong, this whole DOM and function libraries arn't bad (ok rather the must of them) and specially jQuery was a really good library, back in 2010. Nowadays, where anyone who uses the Internet Explorer < 11 does it just out of self-hatred and where JavaScript envolves, you don't need jQuery at all. And this Just Vanilla blog post series here on this website should prove that to you!