HTML and CSS Reference
In-Depth Information
where object is a document object, and property is a CSS style property applicable to
that object. For example, the following command mirrors the effect of applying the CSS
font-size style by setting the font size of the first h1 heading in the document to 24 pixels:
document.getElementsByTagName(“h1”)[0].style.fontSize = “24px”;
Notice that because JavaScript does not support hyphens in property names, the CSS
style attribute is formatted in camel case with the hyphens removed and the letter that
would have followed a hyphen capitalized. Thus, the CSS font-size property is entered
as fontSize in the JavaScript code.
You can set the default
page styles of an entire
document by changing
the style property of the
document.body object.
Parsing Style Values
You also can use the style property to retrieve an element's style values, but only for
inline styles—not for styles defined in an embedded or external style sheet. For example,
if an HTML file contained the tag
<div id=”main” style=”width: 200px”>
you could retrieve the style value and store it in a variable using the following command:
var mainWidth = document.getElementById(“main”).style.width;
In this case, the mainWidth variable would contain the text string 200px . If you needed
to extract the numeric value, you would use the parseInt() method described in an
earlier tutorial as follows:
var widthValue = parseInt(mainWidth);
As a result of this command, the widthValue variable would contain the numeric value
200. For non-integer values, you would use the parseFloat() method. Thus, if the Web
document contained the tag
<p id=”firstP” style=”font-size: 1.5em”>…</p>
the following expression would return a numeric value of 1.5:
Setting Inline Styles with JavaScript
• To apply an inline style to a document object, use
object .style. property = text
where object is a page object, property is a CSS property, and text is a text string
setting that property's value.
• To retrieve the integer value of an inline style property, use
parseInt( object .style. property )
where property is a CSS style property that returns a numeric value such as a font
size or a width.
• To retrieve the numeric value of an inline style property, use the following:
parseFloat( object .style. property )
As with HTML attributes, one advantage of the style object is that you can apply
your knowledge of CSS styles to quickly modify the appearance of your document
objects through your JavaScript programs.
Search WWH ::

Custom Search