« Blog Home

§ Javascript function to add css

This javascript is a way to add an extra style node (css) into a page.

This creates a style node and appends it to the head element.  I use this in Greasemonkey to style other stuff I add to certain pages.  I won't go into that here.

Note the var mystyle=""+<r><![CDATA[ etc., works in FF but I think it fails in IE; never tried in Safari.  I don't know the ins and outs of this, but it's basically a way to cheat and have multi-line strings in javascript.  I think.  For other browsers you may have to make the css all in one line.  If you use php, you could use the "multiline_to_single_line_javascript" function from Use iframe contents to change iframe to ajax div.

You may not have to use the setAttribute() function.  Comparing the Use iframe contents to change iframe to ajax div entry, you may be able to use style.type="text/css";


function addmystyle()
  //put the style in first so my div doesn't jump around
  var styles = document.createElement('style');
  styles.setAttribute('type', 'text/css');
  var mystyle=""+<r><![CDATA[
  .mylinksdiv a
    padding:2px 5px;
    color:blue !important;
    font-weight:400 !important;
  .mylinksdiv a:hover
    font-weight:900 !important;
  var newStyle = document.createTextNode(mystyle);
  var headRef = document.getElementsByTagName('head')[0];



last edited on January 14th, 2010 at 2:20 PM


buy site says:

Well, i have faced this problem a lot of times and now i got how to add CSS to my java script. I bookmarked your page and will come back soonly.

August 23rd, 2011 at 7:13 AM

Slashback says:

Thanks! I just used this again in a new project I'm working on, too.

August 2nd, 2011 at 11:00 AM

Logo design says:

Great tip. I was having problem in adding CSS function to my Java script. Your blog post helped me a lot.

August 1st, 2011 at 10:56 PM

Slashback says:

Thank you!

June 15th, 2011 at 7:53 AM

Writing help says:

As for me I think it's really good sollution!

June 15th, 2011 at 5:16 AM

tadd says:

thanks for the post

March 17th, 2010 at 6:00 AM

Add your comment

Email: (Will not be displayed - Privacy policy)
  random image I can't read it!
Give me a different one!
Verify Post: Input the text from the image above to verify this post (helps prevent spam)

« Blog Home

Oppuk gazed down at the creature in disgust.  Not only had it forced its barbaric name upon him, it smelled of floral aromatics, which the denizens of this world often applied to themselves in the mistaken belief that the natural scents of their bodies were noisome, while blatant artificial odors were somehow more acceptable.
Oppuk, The Course of Empire, Eric Flint & K.D. Wentworth