Created
June 27, 2014 16:18
-
-
Save zz85/fc3f19857811516ac971 to your computer and use it in GitHub Desktop.
Easy way for creating and modifying CSS Rules in JS
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
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! | |
} |
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
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