CSSRuleList
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
ACSSRuleList represents an ordered collection of read-onlyCSSRule objects.
While theCSSRuleList object is read-only, and cannot be directly modified, it is considered alive object, as the content can change over time.
To edit the underlying rules returned byCSSRule objects, useCSSStyleSheet.insertRule() andCSSStyleSheet.deleteRule(), which are methods ofCSSStyleSheet.
This interface was anattempt to create an unmodifiable list and only continues to be supported to not break code that's already using it. Modern APIs represent list structures using types based on JavaScriptarrays, thus making many array methods available, and at the same time imposing additional semantics on their usage (such as making their items read-only).
These historical reasons do not mean that you as a developer should avoidCSSRuleList. You don't createCSSRuleList objects yourself, but you get them from APIs such asCSSStyleSheet.cssRules andCSSKeyframesRule.cssRules, and these APIs are not deprecated. However, be careful of the semantic differences from a real array.
In this article
Instance properties
CSSRuleList.lengthRead onlyReturns an integer representing the number of
CSSRuleobjects in the collection.
Instance methods
CSSRuleList.item()Gets a single
CSSRule.
Examples
In the following example there is a stylesheet with three rules. UsingCSSStyleSheet.cssRules returns aCSSRuleList, which is printed to the console.
The number of rules in the list is printed to the console usingCSSRuleList.length. The firstCSSRule can be returned by using0 as the parameter forCSSRuleList.item, in the example this will return the rules set for thebody selector.
CSS
body { font-family: system-ui, -apple-system, sans-serif; margin: 2em;}.container { display: grid; grid-template-columns: repeat(auto-fill, 200px);}.container > * { background-color: #3740ff; color: white;}JavaScript
let myRules = document.styleSheets[0].cssRules;console.log(myRules);console.log(myRules.length);console.log(myRules[0]);Specifications
| Specification |
|---|
| CSS Object Model (CSSOM)> # the-cssrulelist-interface> |