How to use CSSRuleList in Javascript
Individual Styles
The CSSStyleSheet.cssRules
property returns a
CSSRuleList
object that provides access to the individual
styles in the stylesheet.
The members of this object are described in the following table.
Member | Description | Returns |
---|---|---|
item(pos) | Returns the CSS style at the specified index. | CSSStyleRule |
length | Returns the number of styles in the stylesheet. | number |
Each CSS style in the stylesheet is represented by a
CSSStyleRule
object.
The members of the CSSStyleRule
are shown in the following table.
Member | Description | Returns |
---|---|---|
cssText | Gets or sets the text (including the selector) for the style. | string |
parentStyleSheet | Gets the stylesheet to which this style belongs. | CSSStyleSheet |
selectorText | Gets or sets the selector text for the style. | string |
style | Gets an object representing the styles. | CSSStyleDeclaration |
The following code shows how to use the CSSRuleList
.
<!DOCTYPE HTML>
<html>
<head>
<style title="core styles">
p {<!--from w w w.j a v a2 s . c o m-->
border: medium double black;
background-color: lightgray;
}
#block1 {
color: white;
border: thick solid black;
background-color: gray;
}
</style>
</head>
<body>
<p id="block1">
This is a test.
</p>
<p id="block2">
This is a test.
</p>
<div id="placeholder"></div>
<script>
var placeholder = document.getElementById("placeholder");
processStyleSheet();
function processStyleSheet() {
var rulesList = document.styleSheets[0].cssRules;
for ( var i = 0; i < rulesList.length; i++) {
var rule = rulesList.item(i);
var newElem = document.createElement("table");
newElem.setAttribute("border", "1");
newElem.innerHTML += "<tr><td>parentStyleSheet:</td><td>" +
rule.parentStyleSheet.title +
"</td></tr>";
newElem.innerHTML += "<tr><td>selectorText:</td><td>" +
rule.selectorText +
"</td></tr>";
newElem.innerHTML += "<tr><td>cssText:</td><td>" +
rule.cssText +
"</td></tr>";
placeholder.appendChild(newElem);
}
}
</script>
</body>
</html>