Inject multiple css rules with js

by John Perry

HTML

<div></div>
<div class="red"></div>
<div class="blue"></div>

CSS

div {
  background-color: #333;
  width: 100px;
  height: 100px;
}

JavaScript

function cssEngine(rule) {
  var css = document.createElement('style'); // Creates <style></style>
  css.type = 'text/css'; // Specifies the type
  if (css.styleSheet) css.styleSheet.cssText = rule; // Support for IE
  else css.appendChild(document.createTextNode(rule)); // Support for the rest
  document.getElementsByTagName("head")[0].appendChild(css); // Specifies where to place the css
}

// CSS rules
var rule  = '.red {background-color: red}';
    rule += '.blue {background-color: blue}';

// Load the rules and execute
cssEngine(rule);

/* 
In the real world, you'll want to load 
cssEngine after the DOM loads like this:

window.onload = function() {cssEngine(rule)};

*/