RegExp for checking clases

Posted on

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();

Leave a Reply

Your email address will not be published.