DOM METHODS
One of the most useful methods of the DOM is getElementById() .
This method can be used to access any element that has an id
attribute.
One way to create dynamic text effects on a page is to use CSS (Cascading
Style Sheets) styles in combination with getElementByID() to
make dynamic changes in text display. Do the following steps to create a
dynamic change in color and font family in a block of text.
- Create a block of text, such as:
<p>Here is some text in a paragraph.</p>
- Add an id to the <p> tag:
<p id="p1">Here is some text in a paragraph.</p>
- Add two functions in a script block in the head section of the page that use getElementById and CSS styles to change the color and font of the text.
<script type="text/javascript" language="JavaScript">
<!--
function tColor() {
var tColor = document.getElementById ("p1");
tColor.style.color= "red";
tColor.style.fontFamily = "Arial";
}
function tColor2() {
var tColor2 = document.getElementById ("p1");
tColor2.style.color= "blue";
tColor2.style.fontFamily = "Times Roman";
}
// -->
</script>
- Add event handlers to the <p> tag to trigger changes in the text appearance when the events occur.
<p id="p1" onmouseover="tColor2()" onmouseout="tColor()"> Here is some text in a paragraph.</p>
You can add event handlers to the <p> tag if you are using
a browser that supports DOM Level 1+ (Netscape 6+, Internet Explorer 6).
The following is the complete code for this page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<title>ID</title>
<script type="text/javascript" language="JavaScript">
<!--
function tColor2() {
var tColor2 = document.getElementById ("p1");
tColor2.style.color= "blue";
tColor2.style.fontFamily = "Times Roman";
}
function tColor() {
var tColor = document.getElementById ("p1");
tColor.style.color= "red";
tColor.style.fontFamily = "Arial";
}
// -->
</script>
</head>
<body>
<p id="p1" onmouseover="tColor2()" onmouseout="tColor()">
Here is some text in a paragraph.</p>
</body>
</html>
