Reputation: 44862
I'm attempting to append CSS styling to the head of a HTML page like so...
var HEAD = document.getElementsByTagName("head")[0];
s = document.createElement('Style');
s.id = 'cssp';
s.type = 'text/css';
s.innerHTML = ecks.cssp;
HEAD.appendChild(s);
However the CSS located in ecks.cssp
never appears in the HTML page. What am I doing wrong?
Just an fyi, I'm using chrome to test.
Upvotes: 1
Views: 497
Reputation: 104840
There are ways to add a style element, but they are browser dependent, unlike adding a link.
The string must be valid css.
function addStyle(str){
var el= document.createElement('STYLE');
el.type= 'text/css';
el.media= 'screen';
if(el.styleSheet){
// IE
el.styleSheet.cssText= str;
}
else{
// Most browsers
el.appendChild(document.createTextNode(str));
}
document.getElementsByTagName('HEAD')[0].appendChild(el);
}
Upvotes: 3
Reputation: 5476
Just a tip founded on Google and adapted to you:
function loadcss(filename){
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadcss("mystyle.css", "css") //dynamically load and add this .css file
The link also contains the source to load JS.
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
Upvotes: 0