Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created September 14, 2012 00:53
Show Gist options
  • Save cameronism/3719089 to your computer and use it in GitHub Desktop.
Save cameronism/3719089 to your computer and use it in GitHub Desktop.
Set classes on an element from an object
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;
}
// 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