| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule | [Back] [Original] |
Get to know MDN better
This feature is well established and works across many devices and browser versions. Its been available across browsers since July 2015.
The CSSStyleSheet.insertRule()
method inserts a new CSS rule into the current style sheet.
Note:
Although insertRule() is exclusively a method of
CSSStyleSheet, it actually inserts the rule into
CSSStyleSheet.cssRules its internal
CSSRuleList.
insertRule(rule)
insertRule(rule, index)
ruleA string containing the rule to be inserted. What the inserted rule must contain depends on its type:
index OptionalA 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.)
The newly inserted rule's index within the stylesheet's rule-list.
IndexSizeError DOMExceptionThrown if index > CSSRuleList.length.
HierarchyRequestError DOMExceptionThrown if rule 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.
SyntaxError DOMExceptionThrown if more than one rule is given in the rule parameter.
InvalidStateError DOMExceptionThrown if rule is @namespace and the rule-list contains at-rules other than @import and @namespace at-rules.
This snippet pushes a new rule onto the top of my stylesheet.
myStyle.insertRule("#blanc { color: white }", 0);
/**
* 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
* @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(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,
);
}
}
| Specification |
|---|
| CSS Object Model (CSSOM) # dom-cssstylesheet-insertrule |
This page was last modified on Dec 2, 2025 by MDN contributors.
CSSStyleSheetCSSCSSConditionRuleCSSFontFeatureValuesMapCSSFontFeatureValuesRuleCSSFontPaletteValuesRuleCSSFunctionDeclarationsCSSFunctionDescriptorsCSSFunctionRuleCSSGroupingRuleCSSImportRuleCSSKeyframeRuleCSSKeyframesRuleCSSLayerBlockRuleCSSLayerStatementRuleCSSMediaRuleCSSNamespaceRuleCSSPageDescriptorsCSSPageRuleCSSPropertyRuleCSSRuleCSSRuleListCSSStartingStyleRuleCSSStyleDeclarationCSSStylePropertiesCSSStyleRuleCSSSupportsRuleCaretPositionMediaListMediaQueryListScreenStyleSheetStyleSheetListYour blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |