1

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.

4
  • what does ecks.cssp contains? Commented Jan 21, 2011 at 12:06
  • ecks is a HTMLStyleElement, ecks.cssp is the CSS itself. Commented Jan 21, 2011 at 12:11
  • OK... naveen is right... what is ecks? And what does it contain? However you can insert a src="file.css" in the tag so that you'll create a stylesheet linked to an external file. Commented Jan 21, 2011 at 12:13
  • You have tried to print ecks.cssp? Does javascript have access to the content? for examples just trying to do alert(ecks.cssp) Commented Jan 21, 2011 at 12:14

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Don't use setAttribute to set those properties, just use DOM element's properties directly, or in some cases you'll make IE cry.
I wasn't checking navigator compatibility, but thanks for the tip! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.