Main Page

CSSRules

height: 10px;
width: 10px;
margin: 10px;
}
</style>
<script type=”text/javascript”>
function getBackgroundColor() {
var oCSSRules = document.styleSheets[0].cssRules ||
document.styleSheets[0].rules;
alert(oCSSRules[0].style.backgroundColor);
}
</script>
</head>
<body>
<div id=”div1” class=”special”></div>
<input type=”button” value=”Get Background Color”
onclick=”getBackgroundColor()” />
</body>
</html>
When the button is clicked for this example, an alert correctly displays the background color based on
the rule defined as
div.special
.
The
style
object on a rule isn’t read-only; you can modify it as well. But this is where you must be care-
ful, because modifying a CSS rule affects all elements using it on that page. Consider this example:
<html>
<head>
<title>Accessing Style Sheets Example</title>
<style type=”text/css”>
div.special {
background-color: red;
height: 10px;
width: 10px;
margin: 10px;
}
</style>
<script type=”text/javascript”>
function changeBackgroundColor() {
var oCSSRules = document.styleSheets[0].cssRules ||
document.styleSheets[0].rules;
oCSSRules[0].style.backgroundColor = “blue”;
}
</script>
</head>
<body>
<div id=”div1” class=”special”></div>
<div id=”div2” class=”special”></div>
<div id=”div3” class=”special”></div>
<input type=”button” value=”Change Background Color”
onclick=”changeBackgroundColor()” />
</body>
</html>
311
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 311


JavaScript EditorFree JavaScript Editor     Ajax Editor


©