Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a link stylesheet dynamically in the <head> [closed]

How to add a link stylesheet reference to the head of a document ?

I've found this code but it's not working with all browsers, it crashes my IE7 :

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

Thanks

like image 241
belaz Avatar asked Feb 04 '09 16:02

belaz


2 Answers

Internet explorer will support innerHTML, though it adds reflow this would work:

var headHTML = document.getElementsByTagName('head')[0].innerHTML;
headHTML    += '<link type="text/css" rel="stylesheet" href="style.css">';
document.getElementsByTagName('head')[0].innerHTML = headHTML;
like image 175
Alagu Avatar answered Sep 20 '22 13:09

Alagu


In IE, you could try the createStyleSheet method? That takes URL as a parameter. I don't know whether there is an equivalent in FF/chrome though..

--Senthil

like image 36
Rahul Shelke Avatar answered Sep 21 '22 13:09

Rahul Shelke