views:

297

answers:

1

Hi!

I've got a problem with the dynamic style manipulation in IE7 (IE8 is fine). Using javascript I need to add and remove the < link /> node with the definition of css file.

Adding and removing the node as a child of < head /> works fine under Firefox. Unfortunately, after removing it in the IE, although The tag is removed properly, the page style does not refresh.

In the example below a simple css (makes background green) is appended and removed. After the removal in FF the background turns default, but in IE stays green.

index.html

<html>
<head>
</head>
<script language="javascript" type="text/javascript">

var node;

function append(){
    var headID = document.getElementsByTagName("head")[0];       
    node = document.createElement('link');
    node.type = 'text/css';
    node.rel = 'stylesheet';
    node.href = "s.css";
    node.media = 'screen';
    headID.appendChild(node);
}

function remove(){  
    var headID = document.getElementsByTagName("head")[0];      
    headID.removeChild(node);
}
</script>
<body>

<div onClick="append();">
add
</div>

<div onClick="remove();">
remove
</div>

</body>
</html>

And the style sheet:

s.css
body { background-color:#00CC33  }

Here is the live example: http://rlab.pl/dynamic-style/

Is there a way to get it working?

+1  A: 

Rybz, I, personally, would setup an "initial" style sheet to reset back to (also because it helps reset browsers to "my" desired initial settings, not the browser defaults) and when removing the style sheet from the DOM I would insert the one to reset to. I don't know if this will work for what you are trying to do, but it worked for me in the similar situation, and if I remember correctly I was having the same problem as you do, and that fixed it.

Raine
Thank you for your answer, I think it would work correct. But not in my case: in my app stylesheets are to be prepared by the user, so I cannot force the user to additionally create an initial/reset stylesheet.
rybz