Tutorial Inject New CSS Rules

by in , 0

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 a 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>'
  }).appendTo("body");    
}

Usage

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

Demo

More Information

Style injection quirks in IE (Ryan Seddon). Stack Overflow thread.

Leave a Reply