CSSStyleSheet: addRule() method
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see thecompatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
The obsoleteCSSStyleSheet interface'saddRule()legacy method adds a new rule to thestylesheet. You should avoid using this method, and should instead use the more standardinsertRule() method.
In this article
Syntax
addRule(selector, styleBlock, index)Parameters
selectorA string specifying the selector portion of the CSS rule. Thedefault is the string
undefined.styleBlockA string indicating the style block to apply to elements matchingthe
selector. The default is the stringundefined.indexOptionalAn optional index into the stylesheet's
CSSRuleListat which toinsert the new rule. Ifindexis not specified, the next index after thelast item currently in the list is used (that is, the value ofcssStyleSheet.cssRules.length).
Return value
Always returns -1.
Note that due to somewhat esoteric rules about where you can legally insert rules,it's possible that an exception may be thrown. SeeinsertRule() for more information.
Usage notes
This method is implemented by browsers by constructing a string using the templateliteral`${selector}{${styleBlock}}`, then passing it into the standardinsertRule() method.
Therefore, given existing code such as the following:
cssStyleSheet.addRule(selector, styles, 0);You can rewrite this to use the more standardinsertRule() like this:
cssStyleSheet.insertRule(`${selector} {${styles}}`, 0);Specifications
| Specification |
|---|
| CSS Object Model (CSSOM)> # dom-cssstylesheet-addrule> |