CSSRuleList.item

In this chapter you will learn:

  1. Access item in CSS rule list

Access item in CSS rule list

<!DOCTYPE HTML><!-- ja v a  2s .  co  m-->
<html>
<head>
<style title="core styles">
#block1 {
  color: white;
  border: thick solid black;
  background-color: gray;
}

p {
  border: medium double black;
  background-color: lightgray;
}
</style>
</head>
<body>
  <p id="block1">This is a test.</p>
  <p id="block2" style="border: medium dashed blue; color: red; padding: 2px">
    This is a test. 
  </p>
  <button id="pressme">Press Me</button>
  <div id="placeholder"></div>
  <script>
    var placeholder = document.getElementById("placeholder");
    displayStyles();
    document.getElementById("pressme").onclick = function() {
      document.styleSheets[0].cssRules.item(1).style.paddingTop = "10px";
      document.styleSheets[0].cssRules.item(1).style.paddingRight = "12px";
      document.styleSheets[0].cssRules.item(1).style.paddingLeft = "5px";
      document.styleSheets[0].cssRules.item(1).style.paddingBottom = "5px";
      displayStyles();
    }
    function displayStyles() {
      if (placeholder.hasChildNodes()) {
        var childCount = placeholder.childNodes.length;
        for ( var i = 0; i < childCount; i++) {
          placeholder.removeChild(placeholder.firstChild);
        }
      }
      displayStyleProperties(document.styleSheets[0].cssRules.item(1).style);
      displayStyleProperties(document.getElementById("block2").style);
    }
    function displayStyleProperties(style) {
      var newElem = document.createElement("pre");
      newElem.setAttribute("border", "1");
      newElem.innerHTML += style.border + " ";
      newElem.innerHTML += style.color + " ";
            newElem.innerHTML += style.padding + " ";
      newElem.innerHTML += style.paddingTop + " ";
      placeholder.appendChild(newElem);
    }
  </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to set the CSS property
Home » Javascript Tutorial » CSS Style Sheet
CSSStyleSheet
Media Constraints
CSSStyleSheet.disabled
CSSRuleList
CSSRuleList.item
Set property