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();
}
Written by Eric Kinzel
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#String
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#