Last Updated: February 25, 2016
·
411
· dudelorf

RegExp for checking clases

Implementation of a function for toggling class names

function toggleClass(classN, domElem){
    hasClass(classN, domElem) ?
        removeClass(classN, domElem) :
        addClass(classN, domElem);
}

Uses a RegExp to see if element has a class

function hasClass(classN, domElem){
   var rxStr = "\\b" + classN + "\\b";
   var tester = new RegExp(rxStr);
   return tester.test(domElem.className);
}

Function that uses the String object's replace() method with RegExp to easily remove a class name

function removeClass(classN, domElem){
    var tester = new RegExp(("\\s" + classN + "|" + classN + "\\s?"), "g");
   domElem.className = domElem.className.replace(tester, "");
}

Simple string concatenation to add a class name

function addClass(className, domElem){
   domElem.className = (domElem.className +" " + classN).trim();
}

2 Responses
Add your response

Using String.prototype.indexOf to check if a class is already set is problematic if you don't split the string into an array first. It might be safer to rely on jQuery's addClass/removeClass/toggleClass or classList if possible

over 1 year ago ·

Thanks for the comment. I see how it could be a problem: if classes shared a similar name (eg. car and cardboard) the String.prototype.indexOf method could return a false positive.

over 1 year ago ·