1. Computing & Technology

JavaScript By Example

Document Object Model: 11. Get Styles

From , former About.com Guide

We don't just have access to the HTML from JavaScript, we can also access the CSS. We do this via the style object that is attached to each node. The properties of this style object provide access to all of the defined styles that are attached to the node (note that it does not provide access to any style values that are picked up from the browser defaults).

The naming of the properties to access the style information is slightly more complicated than that for referencing attributes because there are no hyphens in the property names. Where the particular style that you are referenceing (eg. background-color) contains a hyphen the property name capitalises the following letter and removes the hyphen (so background-color is referenced using the backgroundColor property. Styles that do not contain a hyphen all use the same name for the property as for the style being referenced with one exception. Since float is a reserved word the property used to access it has a different name with some browsers calling it cssFloat and others using styleFloat. If you need to reference float then you should check both of these to see which one contains a value.

The one other thing that you need to watch out for when retrieving styles is that there are sometimes multiple ways to represent the same style (in our example the background-color is set to #000 but the same colour can also be represented using #000000, rgb(0,0,0) and black. When retrieving such a value different browsers can return the value using any of these different alternatives without regard to which is used in the actual CSS. You would need to test for all four possible values if you are trying to determine if the background colour is black.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example D1</title>
</head>
<body>
<form action="#">
<div>
<input type="radio" id="r1" name="size" value="s">
<label for="r1">Small</label>
<input type="radio" id="r2" name="size" value="m">
<label for="r2">Medium</label>
<input type="radio" id="r3" name="size" value="l">
<label for="r3">Large</label>
</div>
</form>
<p id="txt"></p>
<script type="text/javascript" src="exampleD1.js"></script>
</body>
</html>

CSS


input {background-color : #000; }

JavaScript


var rad, tx;
rad = document.getElementById('r1');
tx = 'The background colour of the first radio button is "' +
  rad.style.backgroundColor + '"';
document.getElementById('txt').innerHTML = tx;

©2012 About.com. All rights reserved.

A part of The New York Times Company.