September 23, 2001 - Manipulating Style Attributes
September 23, 2001 Manipulating Style Attributes Tips: September 2001
Yehuda Shiran, Ph.D.
|
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:
<STYLE TYPE="text/css">
.rule1
{
width: 5.5in;
height: 8in;
}
.rule2
{
border-left: 1 solid black;
border-top: 1 solid black;
}
</STYLE>
<STYLE TYPE="text/css">
.rule3
{
margin: 1in;
background: white;
}
.rule4
{
position: absolute;
top: .25in;
}
</STYLE>
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
:
document.styleSheets[0].rules[0].style.width
and
document.styleSheets[0].rules[0].style.height
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:
document.styleSheets[0].rules[1].style.borderLeft
and
document.styleSheets[0].rules[0].style.borderTop
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.