このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

CSSStyleSheet: insertRule() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

CSSStyleSheet.insertRule() メソッドは、新しい CSS ルール現在のスタイルシートに挿入します。

メモ: insertRule()CSSStyleSheet 専用のメソッドですが、実際にはルールを CSSStyleSheet.cssRules に、内部的には CSSRuleList に挿入します。

構文

js
insertRule(rule) insertRule(rule, index) 

引数

rule

挿入されるルールが入った文字列です。どのようなルールを挿入するかは、種類によります。

index 省略可

stylesheet.cssRules.length 以下の正の数で、 CSSStyleSheet.cssRules の中で新しく挿入されるルールの位置を示します。既定値は 0 です。(古い実装では、これは必須でした。詳しくはブラウザーの互換性を参照してください。)

返値

スタイルシートのルールリスト内の、新たに挿入されたルールの位置です。

例外

IndexSizeError DOMException

index > CSSRuleList.length の場合に発生します。

HierarchyRequestError DOMException

CSS の制約上、ruleindex 0 に挿入できない場合に発生します。

SyntaxError DOMException

rule 引数に 2 つ以上のルールが与えられた場合に発生します。

HierarchyRequestError DOMException

スタイルルールの後に @import アットルールを挿入しようとした場合に発生します。

InvalidStateError DOMException

rule@namespace であり、ルールリストに @import アットルールや @namespace アットルール以外のものがあった場合に発生します。

新しいルールの挿入

このスニペットは、新しいルールをスタイルシートの先頭に追加します。

js
myStyle.insertRule("#blanc { color: white }", 0); 

スタイルシートルールを追加する関数

js
/** * 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 i = 0; i < rules.length; i++) { let j = 1, rule = rules[i], 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]; j = 0; } for (let pl = rule.length; j < pl; j++) { const prop = rule[j]; 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

ブラウザーの互換性

関連情報