Set property

In this chapter you will learn:

  1. How to set the CSS property

Set CSS property

<!DOCTYPE HTML><!--from  jav a  2  s .  co m-->
<html>
<head>
<style title="core styles">
p {
  color: white;
  border: medium double black;
  background-color: gray;
  padding-top: 5px;
}
</style>
</head>
<body>
  <p id="block1">This is a test.</p>
  <div>
    <button id="pressme">Press Me</button>
  </div>
  <div id="placeholder"></div>
  <script>
    var placeholder = document.getElementById("placeholder");
    displayStyles();
    document.getElementById("pressme").onclick = function() {
      var styleDeclr = document.styleSheets[0].cssRules[0].style;
      styleDeclr.setProperty("background-color", "lightgray");
      styleDeclr.setProperty("padding-top", "20px");
      styleDeclr.setProperty("color", "black");
      displayStyles();
    }
    function displayStyles() {
      if (placeholder.hasChildNodes()) {
        var childCount = placeholder.childNodes.length;
        for ( var i = 0; i < childCount; i++) {
          placeholder.removeChild(placeholder.firstChild);
        }
      }
      var newElem = document.createElement("pre");
      newElem.setAttribute("border", "1");
      var style = document.styleSheets[0].cssRules[0].style;
      newElem.innerHTML+="border"+ style.getPropertyValue("border");
      newElem.innerHTML+="color"+ style.getPropertyValue("color");
      newElem.innerHTML+="padding-top" +style.getPropertyValue("padding-top");
      newElem.innerHTML+="background-color"+style.getPropertyValue("background-color");
      placeholder.appendChild(newElem);
    }
  </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Getting Started with the Canvas Element
Home » Javascript Tutorial » CSS Style Sheet
CSSStyleSheet
Media Constraints
CSSStyleSheet.disabled
CSSRuleList
CSSRuleList.item
Set property