/ Published in: JavaScript
Standard hasClass, addClass, and removeClass functions.
- reworked so that jsLint is happy about them
- removeClass function trims things after removing a class name
- tests help to ensure that all common use-cases are covered
- reworked so that jsLint is happy about them
- removeClass function trims things after removing a class name
- tests help to ensure that all common use-cases are covered
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function hasClass(el, className) { var regEx = new RegExp("(^|\\s)" + className + "(\\s|$)"); return el.className.match(regEx) !== null; } function addClass(el, className) { if (hasClass(el, className)) { return el; } if (!el.className) { el.className = className; } else { el.className = el.className + " " + className; } return el; } function removeClass(el, className) { var regEx = new RegExp("(^|\\s)" + className + "(\\s|$)"); var newClass = el.className.replace(regEx, " "); if (hasClass(el, className)) { el.className = newClass.replace(/^\s+|\s+$/g, ""); } return el; } // What follows are a number of tests to ensure that the above functions work as expected. function makeEl(classNames) { var el = document.createElement("div"); el.className = classNames; return el; } var classes = "apple banana carrot"; console.assert(makeEl("").className === "", "should be empty"); console.assert(makeEl(classes).className === classes, "should have classes"); console.assert(hasClass(makeEl(""), "apple") === false, "shouldn't have apple"); console.assert(hasClass(makeEl(classes), "apple"), "should have apple"); console.assert(hasClass(makeEl(classes), "banana"), "should have banana"); console.assert(hasClass(makeEl(classes), "carrot"), "should have carrot"); console.assert(hasClass(makeEl(classes), "app") === false, "shouldn't have app"); console.assert(addClass(makeEl(""), "apple").className === "apple", "should be apple"); console.assert(addClass(makeEl(classes), "date").className === "apple banana carrot date", "should have date"); console.assert(removeClass(makeEl(""), "").className === "", "should be empty"); console.assert(removeClass(makeEl(""), "apple").className === "", "can't remove what isn't there"); console.assert(removeClass(makeEl(classes), "").className === classes, "can't remove nothing"); console.assert(removeClass(makeEl(classes), "app").className === classes, "shouldn't remove what isn't there"); console.assert(removeClass(makeEl(classes), "apple").className === "banana carrot", "shouldn't have apple"); console.assert(removeClass(makeEl(classes), "banana").className === "apple carrot", "shouldn't have banana"); console.assert(removeClass(makeEl(classes), "carrot").className === "apple banana", "shouldn't have carrot");