tomhoppe.com

Dynamically adding CSS through Javascript

I found this little tip by accident while surfing the web to solve a different problem. Thanks to the Yahoo User Interface Blog for the solution!

When adding in a piece of HTML dynamically, what do you do with the styles for it? In the past, I usually included the styles in a global or page specific stylesheet where I knew the HTML would show up. The current snippet I was writing through, was going to add some code in random places throughout a 4000+ page website as well as some partner sites, so it needed to come with its own CSS. FF allows you nicely to just embed a <style> tag anywhere in a page with your styles and be done with it. IE and Safari, not so much.

What I found on the YUI Blog was the cssText property of the stylesheet property. This allows for a cross browser way for us to insert a string of css into a style element in the head. Beautiful! Just create your css as a string and pass it into the addCSS function below.

function addCss(cssCode) {
var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

9 Responses to “Dynamically adding CSS through Javascript”

  1. Chris Wible says:

    thank you! I’ve been beating my head on the desk for an hour on this one. You rock.

  2. Patrick Fitzgerald says:

    If using jQuery, the following works:

    $(‘<style type=”text/css”>#foo { background: #000; } </style>’).appendTo(“head”);

  3. Dan says:

    Cool, thanks.

  4. Mike Pelton says:

    Well I was close, but I wouldn’t have got to this without your help. Many thanks indeed!

  5. Hemant Negi says:

    Thank you Very much This Helped A lot.
    I was messing my head with the stupid ie thing not working by just innerHTML,
    Appreciable Help Thaks…. Good LUCK..

  6. [...] work. I have attempted to comment where it makes most sense. As you can see, this is adapted from this site, however I had to build in a lot more dynamicity: function addNode(nodeType, secondParm, [...]

  7. Vinod says:

    Awesome!! thx :)

  8. Kim says:

    Thank you! This is just what I needed, and thankfully didn’t have to search long to find it.

  9. Tuan Jinn says:

    Awesome, mate.

Leave a Reply