There are occasions when you do not know what stylesheet to use at design time and must make this decision at runtime. Depending on your target audience JavaScript may be the method you wish to use to implement this.

To any developer that is familiar with JavaScript, DOM in particular, they may think this will be a simple task. Well, it should be but Internet Explorer doesn’t play nice in this case. Should we be surprised?

The logical, and standards compliant way, would be to do this.

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);

Seems simple enough. Now this method will work when applying the stylesheet to the parent page but if you use this method to apply it to the head of an iframe then you will get problems in IE.

Let’s take a look at some code, assuming we have an iframe on the page witht he name “frame”:

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";

var iframe;
if(document.frames)
	iframe = document.frames["frame"];
else
	iframe = window.frames["frame"];
iframe.document.getElementsByTagName("head")[0].appendChild(ss);

You would expect the the above code to work, and it does in every browser except IE. Now this stumped me for quite a while. I search all over Google in search for a solution. After a lot of searching I did find the answer, Google truly is your friends. The code below will work cross browser and apply your stylesheet to your iframe.

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";

var iframe;
if(document.frames)
	iframe = document.frames["frame"];
else
	iframe = window.frames["frame"];
if(document.all)
	iframe.document.createStyleSheet(ss.href);
else
	iframe.document.getElementsByTagName("head")[0].appendChild(ss);

Hopefully this saves you some searching and frustration.