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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access