You already know how to use Cascading Style Sheets to add presentation to your structured XHTML. Now you will learn how to change the presentation under user control with JavaScript.
document.getElementById()
Up to now, you have given a name="" attribute to everything
you want to control. For dynamic HTML, you will give tags an
id="" attribute. These attribute values must
begin with a letter and consist only of letters, digits, and underscores,
and they must be unique. Consider the following paragraph
with a span in it:
This is a paragraph, this is the span, and this is the rest of the paragraph.
<p>This is a paragraph,
<span id="span1">this is the span</span>,
and this is the rest of the paragraph.</p>
<form action="#">
<input type="button" onclick="changeSpan()" value="Change Span"/>
</form>
Let us to change the style of the <span> so that it
has a color of red,
a background-color of light yellow, and
a font-size of 18 point. Here is the code, with line
numbers for reference:
1 function changeSpan( )
2 {
3 var spanObject = document.getElementById("span1");
4
5 spanObject.style.color = "red";
6 spanObject.style.fontSize = "18pt";
7 spanObject.style.backgroundColor = "#ffffcc";
8 }
document.getElementById() function returns a reference
to the object with the id that you specify. In this case,
we want the object with id="span1".color property of the style
attribute of the spanObject to red.font-size and
background-color. However, since you can’t have a
dash in a JavaScript variable name, the rule is to remove the
dash and capitalize the next letter.
If you are running older browsers, this won’t work, because the
browser doesn’t support the getElementById() method.
Rather than writing code to look at navigator.appName
and navigator.appVersion, you should instead check to see
if the capability exists.
function changeSpan( )
{
if (document.getElementById)
{
var spanObject = document.getElementById("span1");
spanObject.style.color = "red";
spanObject.style.fontSize = "18pt";
spanObject.style.backgroundColor = "#ffffcc";
}
else
{
window.status="Sorry, this feature not available.";
}
}
Important: the if statement does not use
the parentheses! You don’t want to call the method; you just want
to see if that method name exists in the document.