CSSRuleList

In this chapter you will learn:

  1. 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.

MemberDescriptionReturns
item(pos)Returns the CSS style at the specified index.CSSStyleRule
lengthReturns 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.

MemberDescriptionReturns
cssTextGets or sets the text (including the selector) for the style.string
parentStyleSheetGets the stylesheet to which this style belongs.CSSStyleSheet
selectorTextGets or sets the selector text for the style.string
styleGets an object representing the styles.CSSStyleDeclaration

The following code shows how to use the CSSRuleList.

<!DOCTYPE HTML><!-- j  a  v a  2s .  c  om-->
<html>
<head>
<style title="core styles">
p {
  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>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Access item in CSS rule list
Home » Javascript Tutorial » CSS Style Sheet
CSSStyleSheet
Media Constraints
CSSStyleSheet.disabled
CSSRuleList
CSSRuleList.item
Set property