CSSStyleSheet

In this chapter you will learn:

  1. Working with CSSStyleSheet through Javascript

CSSStyleSheet

You access the CSS stylesheets available in your document using the document.styleSheets property. document.styleSheets property returns a collection of objects representing the stylesheets as CSSStyleSheet[].

Each stylesheet is represented by a CSSStyleSheet object. CSSStyleSheet object provides the set of properties and methods for manipulating the styles.

MemberDescriptionReturns
cssRulesReturns the set of rules in the stylesheet.CSSRuleList
deleteRule(pos)Removes a rule from the stylesheet.void
disabledGets or sets the disabled state of the stylesheet.boolean
hrefReturns the href for linked stylesheets.string
insertRule(rule, pos)Inserts a new rule into the stylesheet.number
mediaReturns the set of media constraints applied to the stylesheet.MediaList
ownerNodeReturns the element in which the style is defined.HTMLElement
titleReturns the value of the title attribute.string
typeReturns the value of the type attribute.string

The following code gets Basic Information About Stylesheets

<!DOCTYPE HTML><!-- jav a 2 s  . c o m-->
<html>
<head>
<style title="core styles">
p {
  border: medium double black;
  background-color: lightgray;
}

#block1 {
  color: white;
}
</style>
<link rel="stylesheet" type="text/css" href="styles.css" />
<style media="screen AND (min-width:500px)" type="text/css">
#block2 {
  color: yellow;
  font-style: italic
}
</style>
</head>
<body>
  <p id="block1">This is a test.</p>
  <p id="block2">This is a test.</p>
  <div id="placeholder" />
  <script>
    var placeholder = document.getElementById("placeholder");
    var sheets = document.styleSheets;
    for ( var i = 0; i < sheets.length; i++) {
      var newElem = document.createElement("table");
      newElem.setAttribute("border", "1");
      newElem.innerHTML += "<tr><td>index:</td><td>" + i + "</td></tr>";
      newElem.innerHTML += "<tr><td>href:</td><td>" + sheets[i].href + "</td></tr>";
      newElem.innerHTML += "<tr><td>title:</td><td>" + sheets[i].title + "</td></tr>";
      newElem.innerHTML += "<tr><td>type:</td><td>" + sheets[i].type + "</td></tr>";
      newElem.innerHTML += "<tr><td>ownerNode:</td><td>" + sheets[i].ownerNode.tagName + "</td></tr>";

      placeholder.appendChild(newElem);
    }
    function addRow(elem, header, value) {
      
    }
  </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

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