MDN wants to talk to developers like you:

insertRule Redirect 1

The CSSStyleSheet.insertRule() method inserts a new style rule into the current style sheet.

For rule sets this contains both the selector and the style declaration. For at-rules, this specifies both the at-identifier and the rule content. If several rules are given in the DOMString in parameter a DOMException with the code SYNTAX_ERR is thrown.


stylesheet.insertRule(rule, index)


  • rule is a DOMString containing the rule to be inserted (selector and declaration).
  • index is a unsigned int representing the position to be inserted.


Example 1

// push a new rule onto the top of my stylesheet
myStyle.insertRule("#blanc { color: white }", 0); 

Example 2

 * Add a stylesheet rule to the document (may be better practice, however,
 *  to dynamically change classes, so style information can be kept in
 *  genuine styesheets (and avoid adding extra elements to the DOM))
 * Note that an array is needed for declarations and rules since ECMAScript does
 * not afford a predictable object iteration order and since CSS is 
 * order-dependent (i.e., it is cascading); those without need of
 * cascading rules could build a more accessor-friendly object-based API.
 * @param {Array} rules Accepts an array of JSON-encoded declarations
 * @example
  ['h2', // Also accepts a second argument as an array of arrays instead
    ['color', 'red'],
    ['background-color', 'green', true] // 'true' for !important rules 
    ['background-color', 'yellow']
function addStylesheetRules (decls) {
  var styleEl = document.createElement('style');
  // Apparently some version of Safari needs the following line? I dunno.
  var s = styleEl.sheet;
  for (var i=0, rl = rules.length; i < rl; i++) {
    var j = 1, rule = rules[i], selector = decl[0], propStr = '';
    // If the second argument of a rule is an array of arrays, correct our variables.
    if ([1][0]) === '[object Array]') {
      rule = rule[1];
      j = 0;
    for (var pl=rule.length; j < pl; j++) {
      var prop = rule[j];
      propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';
    s.insertRule(selector + '{' + propStr + '}', s.cssRules.length);


Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See also

Document Tags and Contributors

 Last updated by: Sheppy,