Main Page

Accessing style sheets

This page displays two collapsible sections. The two
<div/>
elements that are displayed or hidden are
named
divContent1
and
divContent2
. When the
toggle()
function is called, the ID of the
<div/>
to act on is passed in as an argument. If the
<div/>
has
style.display
equal to
none
(meaning that
it is not displayed), the value is switched to
block
(the default for
<div/>
elements); otherwise,
style.display
is set to
none
. This effectively creates collapsible sections on a Web page.
Accessing style sheets
The
style
object is useful for getting the CSS style of an element using the
style
attribute. What it can-
not do is represent the CSS style of an element as defined by a CSS rule or class defined outside of the
style
attribute, such as in a
<style/>
element or an external style sheet. The following example illus-
trates the problem:
<html>
<head>
<title>Runtime Style Example</title>
<style type=”text/css”>
div.special {
background-color: red;
height: 10px;
width: 10px;
margin: 10px;
}
</style>
<script type=”text/javascript”>
function getBackgroundColor() {
var oDiv = document.getElementById(“div1”);
alert(oDiv.style.backgroundColor);
}
</script>
</head>
<body>
<div id=”div1” class=”special”></div>
<input type=”button” value=”Get Background Color”
onclick=”getBackgroundColor()” />
</body>
</html>
In this code, the style for the
<div/>
is defined in the class
special
. When you click the button and
getBackgroundColor()
is called, the alert displays an empty string because the CSS data isn’t stored
there; it is stored in the class. So the question becomes, how do you access the CSS class?
The first step is to get a reference to the style sheet in which the class is defined. To do this, use the
document.styleSheets
collection, which contains references to all the style sheets in an HTML page,
including all
<style/>
elements (which are considered to be full-fledged style sheets by JavaScript).
The DOM specifies a style sheet object as having the following properties:
?
disabled
— Indicates whether the style sheet is disabled.
?
href
— The URL of the style sheet for externally referenced files; for
<style/>
elements this
should be
null
, although Mozilla returns the URL of the HTML page.
309
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 309


JavaScript EditorFree JavaScript Editor     Ajax Editor


©