Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
like image 300
Hakan Avatar asked Feb 12 '12 16:02

Hakan


People also ask

Can we add style using JavaScript?

We can use JavaScript to directly set a style on an element, and we can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.

How do you add a style tag?

The <style> element must be included inside the <head> of the document. In general, it is better to put your styles in external stylesheets and apply them using <link> elements.

Can you set any style to HTML tag using JavaScript?

The HTML DOM allows JavaScript to change the style of HTML elements.

How do you add dynamic styles in HTML?

By calling element. style. color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id .


2 Answers

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%;} \
";
like image 149
Rob W Avatar answered Sep 29 '22 13:09

Rob W


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); 
}
like image 31
kennebec Avatar answered Sep 29 '22 12:09

kennebec