Help from my friends and random people on IE8 Dynamic CSS?
To my five fans (to those reading that aren’t part of the fan 5 crew, my 5 fans are also good friends):
I have a bit of a dilemma in some web coding.
Problem: I need to be able to dynamically inject some CSS rules into a web page through JavaScript. (Long story why, I just do.) In all of my target browsers, various methods would work to inject CSS into a web page via JavaScript. IE8 does not like any of these previous methods. The only way I’ve found so far to get this to work in IE8 is the following hacktastic solution:
function hacktasticSolutionToDynamicCSSInjectionInIE8() {
var myCSS = "<style>.redText{color:#ff0000}</style>";
document.getElementsByTagName("body")[0].innerHTML += myCSS;
}
Using the method above to inject a stylesheet into the body tag via innerHTML so makes me want to gouge my eyes out. But it’s the only thing that seems to work in IE8?
Other things I’ve tried that have failed:
- Inject into the head element
- Inject into some other element within the body
- Use W3C element creation and appending methods
Anyone reading this who knows of a better solution than what I’ve done in the hacktastic function above?
Edit: 7/3/2009
Turns out in all my tests, Internet Explorer tends to provide a “free” stylesheet by default. The following code did what I wanted on all IEs, and everywhere else.
if ( document.styleSheets[0] && document.styleSheets[0].cssText ) {
document.styleSheets[0].cssText += cssString;
} else {
var style = document.createElement("style");
style.appendChild(document.createTextNode(cssString));
document.getElementsByTagName("head")[0].appendChild(style);
}
Comments
Leave a Reply