Java Reference
In-Depth Information
In some cases, however, the property name is a little different from the one seen in a CSS file. CSS
properties that contain a hyphen (
‐
) are a perfect example of this exception. In the case of these
properties, you remove the hyphen and capitalize the first letter of the word that follows the hyphen.
The following code shows the incorrect and correct ways to do this:
divAdvert.style.background-color = "gray"; // wrong
divAdvert.style.backgroundColor = "gray"; // correct
You can also use the
style
object to retrieve styles that have previously been declared. However,
if the
style
property you try to retrieve has not been set with the
style
attribute (inline styles) or
with the
style
object, you will not retrieve the property's value. Consider the following HTML
containing a style sheet and
<div/>
element:
<style>
#divAdvert {
background-color: gray;
}
</style>
<div id="divAdvert" style="color: green">I am an advertisement.</div>
When the browser renders this element, it will have green text on a gray background. If you had
used the
style
object to retrieve the value of both the
background‐color
and
color
properties,
you'd get the following mixed results:
var divAdvert = document.getElementById("divAdvert");
alert(divAdvert.style.backgroundColor); // alerts an empty string
alert(divAdvert.style.color); // alerts green
You get these results because the
style
object maps directly to the
style
attribute of the element. If
the style declaration is set in a
<style/>
element, or in an external style sheet, you cannot retrieve
that property's value with the
style
object.
Using the style Object
trY it out
Let's look at a simple example of changing the appearance of some text by using the
style
object. Type
the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 9, Example 4</title>
<style>
#divAdvert {
font: 12pt arial;
}
</style>
</head>