CSSStyleSheet.insertRule()

  • Revision slug: Web/API/CSSStyleSheet.insertRule
  • Revision title: CSSStyleSheet.insertRule
  • Revision id: 453073
  • Created:
  • Creator: teoli
  • Is current revision? No
  • Comment Moved From Web/API/CSSStyleSheet/insertRule to Web/API/CSSStyleSheet.insertRule

Revision Content

{{DomRef}}

Summary

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 {{domxref("DOMString")}} in parameter a {{domxref("DOMException")}} with the code SYNTAX_ERR is thrown.

Syntax

stylesheet.insertRule(rule, index)

Parameters

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

Examples

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} decls Accepts an array of JSON-encoded declarations
 * @example
addStylesheetRules([
  ['h2', // Also accepts a second argument as an array of arrays instead
    ['color', 'red'],
    ['background-color', 'green', true] // 'true' for !important rules 
  ], 
  ['.myClass', 
    ['background-color', 'yellow']
  ]
]);
 */
function addStylesheetRules (decls) {
  var style = document.createElement('style');
  document.getElementsByTagName('head')[0].appendChild(style);
  if (!window.createPopup) { /* For Safari */
    style.appendChild(document.createTextNode(''));
  }
  var s = document.styleSheets[document.styleSheets.length - 1];
  for (var i=0, dl = decls.length; i < dl; i++) {
    var j = 1, decl = decls[i], selector = decl[0], rulesStr = '';
    if (Object.prototype.toString.call(decl[1][0]) === '[object Array]') {
      decl = decl[1];
      j = 0;
    }
    for (var rl=decl.length; j < rl; j++) {
      var rule = decl[j];
      rulesStr += rule[0] + ':' + rule[1] + (rule[2] ? ' !important' : '') + ';\n';
    }

    if (s.insertRule) {
      s.insertRule(selector + '{' + rulesStr + '}', s.cssRules.length);
    } else { /* IE */
      s.addRule(selector, rulesStr, -1);
    }
  }
}

Specification

See also

Revision Source

<div>
  {{DomRef}}</div>
<h2 id="Summary" name="Summary">Summary</h2>
<p>The <code><strong>CSSStyleSheet.insertRule()</strong></code> method inserts a new style rule into the current style sheet.</p>
<p>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 {{domxref("DOMString")}} in parameter a {{domxref("DOMException")}} with the code <code>SYNTAX_ERR</code> is thrown.</p>
<h2 id="Syntax" name="Syntax">Syntax</h2>
<pre class="syntaxbox">
<var>stylesheet</var>.insertRule(<var>rule</var>, <var>index</var>)</pre>
<h3 id="Parameters" name="Parameters">Parameters</h3>
<ul>
  <li><code>rule</code> is a {{domxref("DOMString")}} containing the rule to be inserted (selector and declaration).</li>
  <li><code>index</code> is a <code>unsigned int</code> representing the position to be inserted.</li>
</ul>
<h2 id="Examples" name="Examples">Examples</h2>
<h3 id="Example_1" name="Example_1">Example 1</h3>
<pre class="brush: js">
// push a new rule onto the top of my stylesheet
myStyle.insertRule("#blanc { color: white }", 0); 
</pre>
<h3 id="Example_2" name="Example_2">Example 2</h3>
<pre class="brush: js">
/**
 * 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} decls Accepts an array of JSON-encoded declarations
 * @example
addStylesheetRules([
  ['h2', // Also accepts a second argument as an array of arrays instead
    ['color', 'red'],
    ['background-color', 'green', true] // 'true' for !important rules 
  ], 
  ['.myClass', 
    ['background-color', 'yellow']
  ]
]);
 */
function addStylesheetRules (decls) {
  var style = document.createElement('style');
  document.getElementsByTagName('head')[0].appendChild(style);
  if (!window.createPopup) { /* For Safari */
    style.appendChild(document.createTextNode(''));
  }
  var s = document.styleSheets[document.styleSheets.length - 1];
  for (var i=0, dl = decls.length; i &lt; dl; i++) {
    var j = 1, decl = decls[i], selector = decl[0], rulesStr = '';
    if (Object.prototype.toString.call(decl[1][0]) === '[object Array]') {
      decl = decl[1];
      j = 0;
    }
    for (var rl=decl.length; j &lt; rl; j++) {
      var rule = decl[j];
      rulesStr += rule[0] + ':' + rule[1] + (rule[2] ? ' !important' : '') + ';\n';
    }

    if (s.insertRule) {
      s.insertRule(selector + '{' + rulesStr + '}', s.cssRules.length);
    } else { /* IE */
      s.addRule(selector, rulesStr, -1);
    }
  }
}</pre>
<h2 id="Specification" name="Specification">Specification</h2>
<ul>
  <li><a href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-CSSStyleSheet-insertRule">insertRule </a></li>
</ul>
<h2 id="See_also">See also</h2>
<ul>
  <li><a href="/en-US/docs/Web/API/CSSStyleSheet/deleteRule"><code>deleteRule</code></a></li>
</ul>
Revert to this revision