Skip to content

Instantly share code, notes, and snippets.

@zz85
Created June 27, 2014 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zz85/fc3f19857811516ac971 to your computer and use it in GitHub Desktop.
Save zz85/fc3f19857811516ac971 to your computer and use it in GitHub Desktop.
Easy way for creating and modifying CSS Rules in JS
if (!document.styleSheets.length) document.head.appendChild(document.createElement('style'));
var sheet = document.styleSheets[document.styleSheets.length - 1];
var rules = {};
function cssRule(selector, styles) {
var index;
if (selector in rules) {
index = rules[selector];
sheet.deleteRule(index);
} else {
index = rules[selector] = sheet.cssRules.length;
}
sheet.insertRule(selector + " {" + styles + "}", index);
// Don't support for <IE9 sheet.addRule, sorry, ha!
}
cssRule('body', 'background-color: black;')
cssRule('body', 'background-color: white;')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment