Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic inline stylesheet

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.

like image 606
David Hellsing Avatar asked Jan 11 '10 11:01

David Hellsing


1 Answers

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);
    }
like image 86
kennebec Avatar answered Sep 30 '22 08:09

kennebec