Inject New CSS Rules

If you need to change the style of an element with JavaScript, it's typically better to change a class name and have the CSS already on the page take effect and change the style. However, there are exceptions to every rule. For instance, you might want to programmatically change the pseudo-class (e.g. :hover). You can't do that through JavaScript for the same reason inline style="" attributes can't change pseudo classes.

You'll need to inject a new <style> element onto the page with the correct styles in it. Best to inject it at the bottom of the page so it overrides your CSS above it. Easy with jQuery:

function injectStyles(rule) {
  var div = $("<div />", {
    html: '&shy;<style>' + rule + '</style>'


injectStyles('a:hover { color: red; }');


More Information


  1. User Avatar
    Patrick Neal
    Permalink to comment#

    Good post, but wouldn’t it be preferable to simply add a class that solely changes the hover state? For instance add a class of .hoverChange, and in the CSS just add a rule like .hoverChange:hover{ color: red; }?

    • User Avatar
      Chris Coyier
      Permalink to comment#

      Possibly. But you just can’t know every possible situation. Like I mentioned above, what if you need to programmatically calculate what the style will be?

    • User Avatar
      Permalink to comment#

      I like what Patrick has to say, and I like what Chris has to say as well. I think a good compromise for the article would be to mention both patterns and use cases with examples for future readers who may or may not be experienced with CSS.

    • User Avatar
      steve Veerhoff
      Permalink to comment#

      Thanks for this post! In response to Patrick , we are using this function to set defined styles, but the color and background-color are determined by a form input stored in a database. For example, we have a field named sub_unit, and the user determines the name of the sub-unit, which becomes a class. When the form is filled out, font color and background color are chosen by the person filling out the form and applied to the newly defined class.

      Since we have no control over what the sub-unit name is, this snippet allows us to dynamically set CSS when the form data is read.

  2. User Avatar
    Rodney Rehm
    Permalink to comment#

    Isn’t a style element supposed to go in head, since it’s metadata content and all. That is, unless the scope attribute is present… See style element

    • User Avatar
      Chris Coyier
      Permalink to comment#

      Yeah it is, but there’s never been a browser where it didn’t work no matter where you put it. I think think it’s like 0.0001% safer to use body instead of head. Come to think of it, I think the safest possible way is to target the first script tag it can find (there must be one somewhere, since this is JavaScript running) and insert the style element after it.

  3. User Avatar
    Dr. Clue

    This one is actually even a little more fun as you can create pretty much any CSS you could create in a stylesheet, using any of the selectors the browser supports, and they can be

    document.styleSheets[0].insertRule(“body {background:red;}”, 0);

    The 0 is the position index. I actually have a class scribbled up for this stuff that does things like detect and map standards CSS to vendor prefixed , produces re-usable CSS for CSS3D stuff like carousels , cubes , pyramids (with textures),manipulates keyframe rules etc. It will even tell me all the classes that effect an element , elements or even elements matching a regular expression query. The only reason this other stuff is mentioned is simply to point out just how much can actually be done working at the rule level

  4. User Avatar
    Elise Chant
    Permalink to comment#

    It would be better to give the div an id so you can dispose of it easily and instantiate it only once.

    injectStyles: function(id, rule) {
        var $div = "<div id='"+ id +"'><style>"+ rule + "</style></div>";
        if ($('body ' + id).length === 0) {
  5. User Avatar
    Danny Povolotski
    Permalink to comment#

    Agreed. I’m actually quite sure that jQuery popularized a pretty bad approach to CSS styling (inline styles). It’s slow and doesn’t make sense if you think about it (applying CSS to a class doesn’t persist to new elements of that class).

    CSS injection really seems to be the way to go.

    I wrote veinjs just for this purpose:

  6. User Avatar
    Permalink to comment#

    Thanks, very helpful!
    I needed a “no framework” function, so here it is (based on all the above):
    code and demo

  7. User Avatar
    Permalink to comment#

    I have tried to improve upon this post’s code by creating the a js method that would add a style tag dynamically and rule(s) to document body or supplied container element.

    See the link for the working example:

  8. User Avatar

    everytime we click a new div is appended in the body tag, how to remove the existing div and then append?

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.