Last active
December 11, 2015 05:58
-
-
Save fetimo/4555750 to your computer and use it in GitHub Desktop.
A simple collection of functions to add classes, remove classes, and toggle classes on elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Class = (function() { | |
'use strict'; | |
function addClass(el, className) { | |
/** | |
* Adds a string to the class name. | |
* | |
* @param {Node} el Any element | |
* @param {String} className The new class name to add | |
* @return {String} Returns the new className | |
*/ | |
if (el.nodeType === 1 && typeof className === 'string') { | |
el.className += ' ' + className; | |
el.className = el.className.replace(/\s{2,}/g, ' '); | |
return el.className; | |
} | |
} | |
function removeClass(el, className) { | |
/** | |
* Removes a string from the node's class list. | |
* | |
* @param {Node} el Any element | |
* @param {String} className The class name to remove | |
* @return {String} Returns the new className | |
*/ | |
if (el.nodeType === 1 && typeof className === 'string') { | |
return el.className = el.className.replace( | |
new RegExp('(^|\\s+)' + className + '(\\s+|$)', 'g'), | |
'$1' | |
); | |
} | |
} | |
function toggleClass(el, classNames) { | |
/** | |
* Toggles classes on node. | |
* | |
* @param {Node} el Any element | |
* @param {Array} classNames Array of two strings to toggle between | |
* @return {String} Returns the new className | |
*/ | |
if (el.nodeType === 1 && | |
classNames.length === 2 && | |
typeof classNames[0] === 'string' && | |
typeof classNames[1] === 'string') { | |
removeClass(el, classNames[0]); | |
removeClass(el, classNames[1]); | |
addClass(el, classNames[1]); | |
return el.className; | |
} | |
} | |
return { | |
add: addClass, | |
remove: removeClass, | |
toggle: toggleClass | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment