Consider the following example.
img {display:block;border:0;}
The above styles img {display:block;border:0;}
, is referred to as a rule.
Rules have two parts.
The selector indicates what part of the document to which to apply the rule. In the above sample rule, img
is the selector. So, the rule is for any img element in the document.
The declaration block contain one or more declarations. In our sample rule, {display:block;border:0;}
is the declaration block. display:block;
and border:0;
are declarations.
JavaScript represents a CSS rule like img {display:block;border:0;} with a CSSStyleRule
object. They receive the following two members from CSSStyleRule:
selectorText | |
style | |
Then they receive four more from CSSRule: | |
cssText | |
parentRule | |
parentStyleSheet | |
type |
Consider the example img {display:block;border:0;}
For the above sample rule, CSSStyleRule.selectorText would contain "img". So, selectorText contains the rule’s selector as a string. CSSStyleRule.style represents a declaration block like {display:block;border:0;}
with a CSSStyleDeclaration object, which is what the style member contains.
A CSSStyleDeclaration object has the following features listed in the CSSStyleDeclaration interface.
Properties/ Methods |
---|
cssText |
length |
parentRule |
getPropertyCSSValue() |
getPropertyPriority() |
getPropertyValue() |
item() |
removeProperty() |
setProperty() |
For a CSS rule like {display:block;border:0;}
, cssText would contain "display:block;border:0;"
, not {display:block;border:0;}
To simplify querying the property-value pairings within a declaration block, JavaScript extends CSSStyleDeclaration with an optional interface named CSS2Properties that Internet Explorer, Firefox, Safari, and Opera all implement.
So if we had a variable named myDeclarations containing a CSSStyleDeclaration object, it would contain an object equivalent to the following:
var myDeclarations = { display: "block", border: "0", cssText: "display:block;border:0;" }
Example for creating an object literal equivalent to the CSSStyleRule representing the sample rule, img {display:block;border:0;}
.
var myRule = { selectorText: "img", style: { display: "block", border: "0", cssText: "display:block;border:0;" } }