Skip to content

Instantly share code, notes, and snippets.

@newtonapple
Created March 18, 2010 02:01
Show Gist options
  • Save newtonapple/335972 to your computer and use it in GitHub Desktop.
Save newtonapple/335972 to your computer and use it in GitHub Desktop.
// Dynamically loading CSS, the cross browser safe way
function createStyleTag(styleAttributes) {
var styleTag = document.createElement('style');
styleTag.setAttribute('type', 'text/css');
if (styleAttributes) {
for ( var attribute in styleAttributes ) {
styleTag.setAttribute(attribute, styleAttributes[attribute]);
}
}
document.documentElement.firstChild.appendChild(styleTag);
return styleTag;
}
function insertCSS(styleElement, css) {
if ( styleElement ) {
try{
styleElement.innerHTML = css; // browsers that accept innerHTML assignment for style tag
} catch (e) {
try { // Safari uses innerText
style_sheet_element.innerText = css;
} catch(e) { // IE cannot set innerHTML nor innerText. So, we'll use element.styleSheet.addRule
var ss = styleElement.styleSheet;
var selectorsAndRules = css.split(/\s*[{}]\s*/);
var selectors = [];
for (var i=0; i<selectorsAndRules.length; i+=1) {
var selectorsOrRule = selectorsAndRules[i];
if ( selectorsOrRule.charAt(selectorsOrRule.length-1) === ';') { // rule
for (var j=0; j<selectors.length; j+=1) {
ss.addRule(selectors[j], selectorsOrRule);
}
selectors = [];
} else { // selectors: apply each selector using the same rule
selectors.push.apply(selectors, selectorsOrRule.split(','));
}
}
}
}
}
return styleElement;
}
function removeCSS(styleElement) {
if (styleElement) {
styleElement.parentNode.removeChild(styleElement);
}
return styleElement;
}
var css = loadCSS(insertCSS(), 'body, div { background-color:black; border: 1px solid red; } div { margin: 1em; }');
removeCSS(css);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment