Movatterモバイル変換


[0]ホーム

URL:


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

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.

Syntax

js
addRule(selector, styleBlock, index)

Parameters

selector

A string specifying the selector portion of the CSS rule. Thedefault is the stringundefined.

styleBlock

A string indicating the style block to apply to elements matchingtheselector. The default is the stringundefined.

indexOptional

An optional index into the stylesheet'sCSSRuleList at which toinsert the new rule. Ifindex is 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:

js
cssStyleSheet.addRule(selector, styles, 0);

You can rewrite this to use the more standardinsertRule() like this:

js
cssStyleSheet.insertRule(`${selector} {${styles}}`, 0);

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp