Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inject styles into IE8?

// create a style element
$("#main").html('<style id="custom_persona_css"></style>'); 

$("#custom_persona_css").append('#abc{ color:#000000; }');

As you can tell, this does not work in IE8!

How can I make it work in IE8?

There will be an error of : 'unexpected call to method or property access' because IE8 does not recognize the html as valid (abc part)

like image 424
TIMEX Avatar asked Jan 29 '12 02:01

TIMEX


2 Answers

In MSIE set the cssText-property of the styleSheet-object related to the <style/>-element:

   $('<style id="custom_persona_css"></style>').appendTo('head'); 

   if($.browser.msie)
   {
    $("#custom_persona_css").prop('styleSheet').cssText='#abc{ color:#000000; }';
   }
   else
   {
    $("#custom_persona_css").append('#abc{ color:#000000; }');
   }

http://jsfiddle.net/doktormolle/BLJUv/

More Info: http://msdn.microsoft.com/en-us/library/ie/ms533698%28v=vs.85%29.aspx

like image 129
Dr.Molle Avatar answered Nov 11 '22 13:11

Dr.Molle


I agree with jmort253 that perhaps directly modifying style attributes, or loading a css file is best. You can then use the more efficient addClass and removeClass methods. That being said, style elements should be in the head (they work in body of course, but aren't officially supported as I recall). So you can do something like this for that purpose.

http://jsfiddle.net/TCUxx/1

$('head').append('<style type="text/css">#abc{ color:#ff0000; }</style>');

Updated - for some reason this doesn't work. I don't know why. Works in IE9.

var $styleElement = $('<style />', {
    type: 'text/css',
    text: '#abc{ color:#ff0000; }'
});

$('head').append($styleElement);
like image 4
mrtsherman Avatar answered Nov 11 '22 13:11

mrtsherman