CSSStyleSheet: insertRule() method
The CSSStyleSheet.insertRule() method inserts a new CSS rule into the current style sheet.
Syntax
insertRule(rule)
insertRule(rule, index)
Parameters
-
rule
-
A string containing the rule to be inserted. What the inserted rule must contain depends on its type:
index Optional
-
A positive integer less than or equal to stylesheet.cssRules.length, representing the newly inserted rule's position in CSSStyleSheet.cssRules. The default is 0. (In older implementations, this was required. See Browser compatibility for details.)
Return value
The newly inserted rule's index within the stylesheet's rule-list.
Exceptions
IndexSizeError DOMException
-
Thrown if index > CSSRuleList.length.
HierarchyRequestError DOMException
-
Thrown if rule cannot be inserted at index 0 due to some CSS constraint.
SyntaxError DOMException
-
Thrown if more than one rule is given in the rule parameter.
HierarchyRequestError DOMException
-
Thrown if trying to insert an @import at-rule after a style rule.
InvalidStateError DOMException
-
Thrown if rule is @namespace and the rule-list has more than just @import at-rules and/or @namespace at-rules.
Examples
Inserting a new rule
This snippet pushes a new rule onto the top of my stylesheet.
myStyle.insertRule("#blanc { color: white }", 0);
Function to add a stylesheet rule
function addStylesheetRules(rules) {
const styleEl = document.createElement("style");
document.head.appendChild(styleEl);
const styleSheet = styleEl.sheet;
for (let i = 0; i < rules.length; i++) {
let j = 1,
rule = rules[i],
selector = rule[0],
propStr = "";
if (Array.isArray(rule[1][0])) {
rule = rule[1];
j = 0;
}
for (let pl = rule.length; j < pl; j++) {
const prop = rule[j];
propStr += `${prop[0]}: ${prop[1]}${prop[2] ? " !important" : ""};\n`;
}
styleSheet.insertRule(
`${selector}{${propStr}}`,
styleSheet.cssRules.length,
);
}
}
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
insertRule |
1 |
12 |
1 |
9 |
≤12.1 |
1 |
4.4 |
18 |
4 |
≤12.1 |
1 |
1.0 |
index_parameter_optional |
1 |
12 |
55 |
No |
15 |
1 |
4.4 |
18 |
55 |
14 |
1 |
1.0 |
See also