CSSStyleSheet: insertRule()-Methode
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
Die Methode CSSStyleSheet.insertRule()
fügt eine neue CSS-Regel in das aktuelle Stylesheet ein.
Hinweis:
Obwohl insertRule()
exklusiv eine Methode von
CSSStyleSheet
ist, fügt sie die Regel tatsächlich in
[CSSStyleSheet](/de/docs/Web/API/CSSStyleSheet).cssRules
ein — die interne
CSSRuleList
.
Syntax
insertRule(rule)
insertRule(rule, index)
Parameter
rule
-
Ein String, der die einzufügende Regel enthält. Was die eingefügte Regel enthalten muss, hängt von ihrem Typ ab:
- Für Regel-Sets: Sowohl ein Selektor als auch eine Stil-Deklaration.
- Für At-Regeln: Sowohl ein At-Identifikator als auch der Regelinhalt.
index
Optional-
Eine positive ganze Zahl, die kleiner oder gleich
stylesheet.cssRules.length
ist und die Position der neu eingefügten Regel in[CSSStyleSheet](/de/docs/Web/API/CSSStyleSheet).cssRules
darstellt. Der Standardwert ist0
. (In älteren Implementierungen war dies erforderlich. Siehe Browser-Kompatibilität für Details.)
Rückgabewert
Der Index der neu eingefügten Regel innerhalb der Regel-Liste des Stylesheets.
Ausnahmen
IndexSizeError
DOMException
-
Wird ausgelöst, wenn
index
>[CSSRuleList](/de/docs/Web/API/CSSRuleList).length
ist. HierarchyRequestError
DOMException
-
Wird ausgelöst, wenn
rule
aufgrund einer CSS-Beschränkung nicht an Positionindex
0
eingefügt werden kann. SyntaxError
DOMException
-
Wird ausgelöst, wenn im Parameter
rule
mehr als eine Regel angegeben wird. HierarchyRequestError
DOMException
-
Wird ausgelöst, wenn versucht wird, eine
@import
-Regel nach einer Stilregel einzufügen. InvalidStateError
DOMException
-
Wird ausgelöst, wenn
rule
eine@namespace
-Regel ist und die Regel-Liste mehr als nur@import
- und/oder@namespace
-Regeln enthält.
Beispiele
Eine neue Regel einfügen
Dieses Snippet fügt eine neue Regel an den Anfang meines Stylesheets ein.
myStyle.insertRule("#blanc { color: white }", 0);
Funktion zum Hinzufügen einer Stylesheet-Regel
/**
* 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,
);
}
}
Spezifikationen
Specification |
---|
CSS Object Model (CSSOM) # dom-cssstylesheet-insertrule |
Browser-Kompatibilität
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
insertRule() | ||||||||||||
index parameter is optional |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support