Main Page

Computed styles in the DOM

<html>
<head>
<title>Computed 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.currentStyle.backgroundColor);
}
</script>
</head>
<body>
<div id=”div1” class=”special”></div>
<input type=”button” value=”Get Background Color”
onclick=”getBackgroundColor()” />
</body>
</html>
In this example, clicking the button displays the computed background color (red) even though the
background color is defined in the
div.special
rule.
Keep in mind that all properties of the
currentStyle
object are read-only, and you cause an error if you
try to assign a value. This happens because the
currentStyle
object is a summation of all applicable
styles from the element and CSS rules; it is not a living, breathing object. To make style changes dynami-
cally, you must use the
style
object as discussed previously.
Computed styles in the DOM
The DOM provides a method called
getComputedStyle()
that creates a
style
-like object based on a
given element. The method accepts two parameters, the element to get the style for and a pseudo-element,
such as
:hover
or
:first-letter
(it can also be
null
if not needed). You can access this method from the
document.defaultView
object, which is used to represent the currently rendered view of the document
(
document.defaultView
is not supported in Internet Explorer or Safari).
You can rewrite the previous example using DOM methods like this:
<html>
<head>
<title>Computed Style Example</title>
<style type=”text/css”>
div.special {
background-color: red;
height: 10px;
width: 10px;
margin: 10px;
313
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 313


JavaScript EditorFree JavaScript Editor     Ajax Editor


©