Hakan
Hakan

Reputation: 3885

Trying to add style tag using javascript (innerHTML in IE8)

This doesn't work in IE8. I think it's the innerHTML that causes the problem. How to solve?

// jQuery plugin
(function( $ ){

    $.fn.someThing = function( options ) {  

        var d = document,
            someThingStyles = d.createElement('style');

        someThingStyles.setAttribute('type', 'text/css');
        someThingStyles.innerHTML = " \
        .some_class {overflow:hidden} \
        .some_class > div {width:100%;height:100%;} \
        ";
        d.getElementsByTagName('head')[0].appendChild(someThingStyles);

        });

    };

})( jQuery );

Upvotes: 9

Views: 15603

Answers (3)

kennebec
kennebec

Reputation: 104770

If you weren't using jquery, IE before version 9 writes to a style element by assigning a css string to the styleelement.styleSheet.cssText.

Other browsers (including IE9+) let you append text nodes to the element directly.

function addStyleElement(css){
  var elem=document.createElement('style');
  if(elem.styleSheet && !elem.sheet)elem.styleSheet.cssText=css;
  else elem.appendChild(document.createTextNode(css));
  document.getElementsByTagName('head')[0].appendChild(elem); 
}

Upvotes: 9

J. K.
J. K.

Reputation: 8368

You should check out the CSSOM (CSS Object Model) spec - http://dev.w3.org/csswg/cssom/

You will probably be interested in the cssText property of CSSRule objects - http://dev.w3.org/csswg/cssom/#dom-cssrule-csstext

Upvotes: 1

Rob W
Rob W

Reputation: 348992

jQuery

Since you're already using jQuery, use:

 $('<style type="text/css">' + 
   '.some_class {overflow:hidden}' +
    '.some_class > div {width:100%;height:100%;}' +
    '</style>').appendTo('head');

Pure JavaScript

If you don't want to use jQuery, you have to first append the <style> element, then use the style.styleSheet.cssText property (IE-only!!).

var d = document,
    someThingStyles = d.createElement('style');
d.getElementsByTagName('head')[0].appendChild(someThingStyles);
someThingStyles.setAttribute('type', 'text/css');

someThingStyles.styleSheet.cssText = " \
.some_class {overflow:hidden} \
.some_class > div {width:100%;height:100%;} \
";

Upvotes: 14

Related Questions