What is the best way of creating dynamic style tags using js and/or jQuery?
I tried this:
var style= jQuery('<style>').text('.test{}');
This works in FF but pops an error in IE7 "Unexpected call to method or property access."
var style = document.createElement('style');
style.innerHTML='.test{}';
Gives the same error. It doesn't matter if I use innerHTML
or innerText
. The strange thing is that it shows an error before appending the style tag.
I suspect that cssText
has something to do with it, but I'm not sure how.
Adding text to a stylesheet that will be rendered correctly needs a different syntax in IE than other browsers. You may be able to use some of this with jquery
document.addStyle= function(str, hoo, med){
var el= document.createElement('style');
el.type= "text/css";
el.media= med || 'screen';
if(hoo) el.title= hoo;
if(el.styleSheet) el.styleSheet.cssText= str;//IE only
else el.appendChild(document.createTextNode(str));
return document.getElementsByTagName('head')[0].appendChild(el);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With