O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Changing Text Style Properties

NN 6, IE 4

Problem

You want to alter the style of some text already displayed on the page.

Solution

Change one or more of the associated style properties of the element containing the text, as in these examples:

               elementReference.style.color = "00ff00";
elementReference.style.font = 
    "bolder small-caps 16px 'Andale Mono', Arial, sans-serif";
elementReference.style.fontFamily = "'Century Schoolbook', Times, serif";
elementReference.style.fontSize = "22px";
elementReference.style.fontStretch = "narrower";
elementReference.style.fontStyle = "italic";
elementReference.style.fontVariant = "small-caps";
elementReference.style.fontWeight = "bolder";
elementReference.style.textDecoration = "line-through";
elementReference.style.textTransform = "uppercase";

Discussion

Many CSS properties affect the appearance of text on the page. Most of the CSS2-standard properties are implemented in IE 6 and NN 6, with occasional proprietary properties also available. Because all implemented CSS properties can be controlled via properties of the style object associated with an element, those CSS properties can be modified after the page has loaded (in IE 4 or later and NN 6 or later).

Before you can modify the appearance of text, that text must be its own element, even if it is merely an arbitrary span within a larger element. See Recipe 15.2 for an example of converting a user text selection into an element ready for text style modification.

Note that to comply with JavaScript ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required