Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. CSSStyleSheet
  4. insertRule()

CSSStyleSheet: insertRule() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

TheCSSStyleSheet.insertRule()method inserts a newCSS rule into thecurrent style sheet.

Note:AlthoughinsertRule() is exclusively a method ofCSSStyleSheet, it actually inserts the rule intoCSSStyleSheet.cssRules — its internalCSSRuleList.

Syntax

js
insertRule(rule)insertRule(rule, index)

Parameters

rule

A string containing the rule to be inserted. What the insertedrule must contain depends on its type:

indexOptional

A positive integer less than or equal tostylesheet.cssRules.length,representing the newly inserted rule's position inCSSStyleSheet.cssRules. The default is0. (In older implementations, this was required. SeeBrowser compatibility for details.)

Return value

The newly inserted rule's index within the stylesheet's rule-list.

Exceptions

IndexSizeErrorDOMException

Thrown ifindex >CSSRuleList.length.

HierarchyRequestErrorDOMException

Thrown ifrule cannot be inserted at the specified index due to some CSS constraint; for instance: trying to insert an@import at-rule after a style rule.

SyntaxErrorDOMException

Thrown if more than one rule is given in therule parameter.

InvalidStateErrorDOMException

Thrown ifrule is@namespace and therule-list contains at-rules other than@import and@namespace at-rules.

Examples

Inserting a new rule

This snippet pushes a new rule onto the top of my stylesheet.

js
myStyle.insertRule("#blanc { color: white }", 0);

Function to add a stylesheet rule

js
/** * Add a stylesheet rule to the document (it may be better practice * to dynamically change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the DOM). * Note that an array is needed for declarations and rules since ECMAScript does * not guarantee a predictable object iteration order, and since CSS is * order-dependent. * @param {Array} rules Accepts an array of JSON-encoded declarations * @exampleaddStylesheetRules([  ['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(rules) {  const styleEl = document.createElement("style");  // Append <style> element to <head>  document.head.appendChild(styleEl);  // Grab style element's sheet  const styleSheet = styleEl.sheet;  for (let rule of rules) {    let i = 1,      selector = rule[0],      propStr = "";    // If the second argument of a rule is an array of arrays, correct our variables.    if (Array.isArray(rule[1][0])) {      rule = rule[1];      i = 0;    }    for (; i < rule.length; i++) {      const prop = rule[i];      propStr += `${prop[0]}: ${prop[1]}${prop[2] ? " !important" : ""};\n`;    }    // Insert CSS Rule    styleSheet.insertRule(      `${selector}{${propStr}}`,      styleSheet.cssRules.length,    );  }}

Specifications

Specification
CSS Object Model (CSSOM)
# dom-cssstylesheet-insertrule

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp