|
September 23, 2001 Manipulating Style Attributes Tips: September 2001
Yehuda Shiran, Ph.D.
|
|
You can access style definitions in their object form. The STYLE tags are represented in a zero-based collection, document.styleSheets. Each STYLE definition may include one or more rules. Each STYLE definition's rules are represented as a zero-based collection, document.styleSheets[i].rules. Within a rule, style attributes are represented as properties of the style object, which is a property of the rules[j] object. If your page looks like this:
then you'll have two elements in the document.styleSheets collection. The first STYLE definition is stored in document.styleSheets[0], while the second STYLE definition is stored in document.styleSheets[1]. The first STYLE definition includes two rules, rule1 and rule2. They will be stored in the collection document.styleSheets[0].rules. The first rule, rule1, will be stored as document.styleSheets[0].rules[0], while rule2 will be stored as document.styleSheets[0].rules[1]. The style attributes width and height are properties of the object document.styleSheets[0].rules[0].style:
and
Similarly, the style attributes border-left and border-top are properties of document.styleSheets[0].rules[1].style. The only problem is that the dash sign is not acceptable in JavaScript' property names. Therefore, the convention is to omit the dash and make the following character an uppercase. Following this algorithm, the style attribute border-left should become the style property borderLeft, and border-top should be borderTop. The complete property specifications are:
and
We included the above rule definitions in this tip. Convince yourself that the object representation is correct by checking width's and borderLeft's values.
People who read this tip also read these tips: Look for similar tips by subject: |