fatima Na
fatima Na

Reputation: 72

How To append css attributes in <style> tag in IE

I have an ajax web application, loading all parts in a single page such as index.html. Inner parts to be loaded in index.html exceeded 32 page(html, js, css).

Now I have trouble with CSS files to be include or @import. I thought I can merge all styles in a style tag using JS at client side. The problem is, IE doesn't allow me to change the style tag in head of the page using JS.

Any suggestion?

Here is the fiddle of what I want to do in IE. It's working fine in other standard browsers.

Upvotes: 0

Views: 1136

Answers (3)

hector-j-rivas
hector-j-rivas

Reputation: 807

This works in IE 9 and Chrome 22:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <style id="styleTag" type="text/css">
        </style>
        <script type="text/javascript">
        window.onload = function()
        {
            // append a stylesheet to the page's head (optional)
            var el = document.createElement("link"); 

            el.type = "text/css"; 
            el.rel = "stylesheet"; 

            document.getElementsByTagName("HEAD")[0].appendChild(el);

            // get a reference to the newly added stylesheet
            var css = document.styleSheets[document.styleSheets.length - 1];

            // OR get a reference to an existing stylesheet
            // var css = document.styleSheets[0];

            // add rules to the stylesheet
            css.insertRule("body {background:red;}", css.cssRules.length);
        }
        </script>
    </head>
    <body>
        <h1>Hello, world.</h1>
    </body>
</html>

So you want to focus on referencing the style object, parsing your stylesheets' rules and adding them using insertRule.

Upvotes: 0

skobaljic
skobaljic

Reputation: 9644

You can append new stylesheet to <head> instead:

$('head').append('<style >body {background:red;}</style >');

Or you can import styles together with remote pages, they do not have to be in <head> at all.

Upvotes: 1

bukart
bukart

Reputation: 4906

this is a stupid IE bug, well

try to use @import url("extra.css") all; inside of your css files

Upvotes: 0

Related Questions