I found this little tip by accident while surfing the web to solve a different problem. Thanks to the Yahoo User Interface Blog for the solution!
When adding in a piece of HTML dynamically, what do you do with the styles for it? In the past, I usually included the styles in a global or page specific stylesheet where I knew the HTML would show up. The current snippet I was writing through, was going to add some code in random places throughout a 4000+ page website as well as some partner sites, so it needed to come with its own CSS. FF allows you nicely to just embed a <style> tag anywhere in a page with your styles and be done with it. IE and Safari, not so much.
What I found on the YUI Blog was the cssText property of the stylesheet property. This allows for a cross browser way for us to insert a string of css into a style element in the head. Beautiful! Just create your css as a string and pass it into the addCSS function below.
function addCss(cssCode) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
thank you! I’ve been beating my head on the desk for an hour on this one. You rock.
If using jQuery, the following works:
$(‘<style type=”text/css”>#foo { background: #000; } </style>’).appendTo(“head”);
Cool, thanks.
Well I was close, but I wouldn’t have got to this without your help. Many thanks indeed!
Thank you Very much This Helped A lot.
I was messing my head with the stupid ie thing not working by just innerHTML,
Appreciable Help Thaks…. Good LUCK..
[...] work. I have attempted to comment where it makes most sense. As you can see, this is adapted from this site, however I had to build in a lot more dynamicity: function addNode(nodeType, secondParm, [...]
Awesome!! thx