O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

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

Accessing CSS Properties from JavaScript

The textDecoration property I used in an earlier example represents a CSS property that is normally hyphenated, like this: text-decoration. But since JavaScript reserves the hyphen character for use as a mathematical operator, whenever you access a hyphenated CSS property you must omit the hyphen and set the character immediately following it to uppercase.

Another example of this is the font-size property, which is referenced in JavaScript as fontSize when placed after a period operator, like this:

myobject.fontSize = '16pt'

An alternative to this is to be more long-winded and use the setAttribute function, which does support (and in fact requires) standard CSS property names, like this:

myobject.setAttribute('font-size', '16pt')

Warning

Some versions of Microsoft Internet Explorer are picky in certain instances about using the JavaScript-style CSS property names when applying the browser-specific -ms--prefixed versions of the rules. If you encounter this, use the setAttribute function and you should be all right.

Some Common Properties

Using JavaScript you can modify any property of any element in a web document, in a similar manner to using CSS. I have already shown you how to access CSS properties, using either the JavaScript short form or the setAttribute function (to use exact CSS property names). Therefore, I won’t bore you by detailing all of these hundreds of properties. Rather, I’d like to show you how to access just a few of the CSS properties ...

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