Created
September 14, 2012 00:53
-
-
Save cameronism/3719089 to your computer and use it in GitHub Desktop.
Set classes on an element from an object
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
function updateClasses(el, options) { | |
var classes = el.className.split(/\s+/), | |
className, | |
pattern = /^no-(\w+)$/, | |
val, | |
i, l; | |
for (i = 0, l = classes.length; i < l; i++) { | |
className = classes[i]; | |
if (!options.hasOwnProperty(className)) { | |
val = pattern.exec(className); | |
if (val && options.hasOwnProperty(val[1])) { | |
className = val[1]; | |
} | |
} | |
if (options.hasOwnProperty(className)) { | |
val = options[className]; | |
val = | |
val == '1' || val == 'true' ? true : | |
val == '0' || val == 'false' ? false : | |
val; | |
if (typeof val == 'boolean') { | |
classes[i] = val ? className : 'no-' + className; | |
} | |
} | |
} | |
el.className = classes.join(' '); | |
return classes; | |
} |
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
// classes before: no-stuff things | |
updateClasses(document.documentElement, { stuff: true, things: false }); | |
// classes after: stuff no-things |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment