Skizit
Skizit

Reputation: 44862

Trying to append CSS to the head of a HTML page using javascript

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

Answers (2)

kennebec
kennebec

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

Fran Verona
Fran Verona

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

Related Questions