Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Controlling Styles with JavaScript

The new W3C DOM (Document Object Model) makes it easy for JavaScript applications to control the styles on a page. Whether you use style sheets or not, you can use JavaScript to modify the style of any element on a page.

As you learned in Hour 9, "Working with the Document Object Model," the DOM allows you to access the entire HTML document and all of its elements as scriptable objects. You can change any object's style by modifying its style object values.

The names and values of objects under the style object are the same as you've learned in this Hour. For example, you can change an element's color by modifying its style.color attribute:

element.style.color="blue";

Here, element represents the object for an element. There are many ways of finding an element's corresponding object, which you will learn about in detail in Hour 19, "Using Dynamic HTML (DHTML)."

In the meantime, an easy way to find an element's object is to assign an identifier to it with the ID attribute. The following statement creates an <h1> element with the identifier "head1":

<h1 ID = "head1">This is a heading</h1>

Now that you've assigned an identifier, you can use the getElementById method to find the DOM object for the element:

element = document.getElementById("head1");

You can also use a shortcut to set styles and avoid the use of a variable by directly working with the getElementbyId method:

document.getElementById("head1").style.color="blue";

This statement combines the examples above by directly assigning the blue color style to the head1 element of the page. You'll use this technique to create a dynamic page in the Workshop section.

Share ThisShare This

Informit Network