CSSGroupingRule: 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 September 2015.

The insertRule() method of the CSSGroupingRule interface adds a new CSS rule to a list of CSS rules.

Syntax

js
insertRule(rule)
insertRule(rule, index)

Parameters

rule

A string

index Optional

An optional index at which to insert the rule; defaults to 0.

Return value

The index of the new rule.

Exceptions

IndexSizeError DOMException

Thrown if index is greater than the number of child CSS rules.

HierarchyRequestError DOMException

Thrown if, due to constraints specified by CSS, the new rule cannot be inserted into the list at the (zero-index) index position given.

InvalidStateError DOMException

Thrown if the new rule is an @namespace at-rule, and the list of child CSS rules contains anything other than @import at-rules and @namespace at-rules.

Examples

js
let myRules = document.styleSheets[0].cssRules;
myRules[0].insertRule(
  "html {background-color: blue;}",
  0,
); /* inserts a rule for the HTML element at position 0 */

Specifications

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

Browser compatibility

BCD tables only load in the browser