1. Home
  2. Computing & Technology
  3. JavaScript

The Javascript DOM

5. Changing Styles

clr gif

Like the other attributes on a tag, we can access and change the style associated with a given tag when we access it using getElementById. There are two ways in which this differs from the other attributes that we can access. Firstly, the style attribute itself has a large number of sub-attributes that define all of the different aspects of how the object is to be displayed and where it is to be displayed. Secondly, a number of the sub-attributes may have been inherited from a parent container (the reason why cascading stylesheets are called that is that styles can cascade through the different levels within our document). Also the style attribute need not actually appear on the tag itself as any stylesheets attached to the page along with any styles defined in the head of the page will also be applied.

These differences make accessing and changing the style of a container from our HTML document somewhat different from the way that we can access the other properties. To start with not all of the style properties can be accessed directly. The only properties that you can guarantee will be accessible from within Javascript are those that you have previously set using Javascript. Those properties that have cascaded down to be inherited from a parent container will almost certainly not be accessible to be read from the current object.

Another difference is that each sub-attribute of the style attribute needs to be referenced separately. You cannot just retriev or write all of the style data for your object in one go.

var y = document.getElementById('thisfield');
var t = y.style.top;
var l = y.style.left;

Updating the style associated with an element of our web page is particularly useful as we can completely change the appearance of the object, change where the object appears, or even choose whether or not the object is to appear at all. Manipulating the style of an object on our web page is the basis of being able to animate the content of our page.

Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.