Created
September 28, 2009 14:51
-
-
Save paolochiodi/195485 to your computer and use it in GitHub Desktop.
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(){ | |
var newStylesheet = null; | |
window.addCssClass = function (selector, content){ | |
// ensure presence of head element | |
if(typeof selector === 'string'){ | |
console.log('creating'); | |
if(!newStylesheet){ | |
var headElement = document.getElementsByTagName('head'); | |
if(!headElement.length){ | |
var htmlElement = document.getElementsByTagName('html'); | |
if(htmlElement.length === 0) return; | |
htmlElement = htmlElement[0]; | |
headElement = document.createElement('head'); | |
htmlElement.insertChild(headElement, htmlElement.firstChild); | |
}else{ | |
headElement = headElement[0]; | |
} | |
var styleElement = document.createElement("style"); | |
styleElement.type = "text/css"; | |
// add to <head> | |
headElement.appendChild(styleElement); | |
if(document.styleSheets){ | |
var sss = document.styleSheets; | |
newStylesheet = sss[sss.length - 1]; | |
} | |
} | |
if(newStylesheet){ | |
// stringify content | |
var style = stringify(content), | |
rules = (newStylesheet.cssRules || newStylesheet.rules); | |
if(newStylesheet.insertRule){ | |
newStylesheet.insertRule(selector + '{' + style + '}', rules.length); | |
}else if(newStylesheet.addRule){ | |
newStylesheet.addRule(selector, style) | |
} | |
return rules[rules.length - 1]; | |
} | |
}else{ | |
// stringify content | |
selector.style.cssText = stringify(content); | |
return selector; | |
} | |
} | |
function stringify(obj){ | |
var style = ''; | |
for(var attribute in obj){ | |
style += attribute + ':' + obj[attribute] + ';'; | |
} | |
return style | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment