Categories:

JavaScript Kit > DOM Reference > Here

DOM CSS Rule Object

Last updated: Februrary 27th, 2006

The CSS Rule object of the StyleSheet object allows you to access and modify the individual rules of a stylesheet. IE and Firefox varies in their implementation of the CSS Rule object, though luckily, the difference is mainly in the syntax:

document.styleSheets[0].cssRules[0] //access the first rule in Firefox
document.styleSheets[0].rules[0] //access the first rule in IE Win

CSS Rule Object

As mentioned, IE and Firefox relies on two different CSS Rule objects to access a stylesheet's rules. Below lists the two objects:

Properties Description
cssRules[] DOM2 based CSS Rule object. Supported in NS/ Firefox.
rules[] IE's CSS Rule object.

Example(s):

if (document.styleSheets[0].cssRules)
crossrule=document.styleSheets[0].cssRules[0]
else if (document.styleSheets[0].rules)
crossrule=document.styleSheets[0].rules[0]

Properties

Properties Description
cssText Returns the content of a css rule in its entirety, from the selector to the corresponding CSS declaration(s). NS/Firefox only. A useful property to easily search within a rule, by looking at both the selector and attributes of a rule all at once.

Example(s):

if (document.styleSheets[0].cssRules[0].cssText.indexOf("float")!=-1)
//this rule has a float attribute defined somewhere

length Returns the length of the CSS Rule object (cssRules.length or rules.length), in other words, the number of rules within a stylesheet.
parentStyleSheet Returns the styleSheet object that contains the current rule.
selectorText Read/write property that returns the selector part of a rule. Setting this property yields unpredictable results in both Firefox and IE.

Example(s):

var mysheet=document.styleSheets[0]
for (i=0; i<mysheet.cssRules.length; i++){
if (mysheet.cssRules[i].selectorText=="p"){ //find the first "p" rule within stylesheet
pobj=mysheet.cssRules[i]
break
}
}

style The "style" object of the css rule object provides read/write access to individual attributes defined in the rule, similar in fashion to the "style" object of inline styles.

Example(s):

var mysheet=document.styleSheets[0]
if (mysheet.cssRules[0].style.backgroundColor!="yellow")
mysheet.cssRules[0].style.backgroundColor="yellow"


Sponsored By

DD CSS Library
Free CSS menus and codes to give your site a visual boost.

DOM Window
DOM Document
DOM Element
DOM Event
DOM Style
DOM Table
Miscellaneous

 

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info