views:

161

answers:

3

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.

A: 

I would look into Javascript's document.styleSheets, and the addRule() method.

(Disclaimer: I've never actually used this myself)

Joel L
A: 

This method of generating css rules dynamically will be flawed even if it worked. IE will simply ignore <style> elements after more then 30 have been inserted (see http://support.microsoft.com/kb/262161).

You can use the jquery.rule plugin for the purpose of manipulating css rules through javascript.

Martijn Laarman
+2  A: 

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);
    }
kennebec
Works great. jQuery should abstract this! Any performance issues you know about?
David
I often use it with a cookie to persist user display preferences onload, and sometimes to make large style changes on a page instead of looping through elements and applying individual styles.It has worked well for years in IE,firefox,opera, and safari, even when the stylesheet rules methods were less well supported.
kennebec
David see my post for a an abstracted jQuery plugin and notes on using this method in IE.
Martijn Laarman