Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Modifying Text within a Page

Next, you can create a simple script to modify the contents of a heading within a Web page. As you learned earlier this hour, the nodeValue property of a text node contains its actual text, and the text node for a heading is a child of that heading. Thus, the syntax to change the text of a heading with the identifier head1 would be:

Var head1=document.getElementById("head1");
Head1.firstChild.nodeValue="New Text Here";

This assigns the variable head1 to the heading's object. The firstChild property returns the text node that is the only child of the heading, and its nodeValue property contains the heading text.

Using this technique, it's easy to create a page that allows the heading to be changed dynamically. Listing 20.2 shows the complete HTML document for this script.

Example 20.2. The Complete Text-Modifying Example

<html>
<head>
<title>Dynamic Text in JavaScript</title>
<script language="Javascript" type="text/javascript">
function ChangeTitle() {
   var newtitle = document.form1.newtitle.value;
   var head1 = document.getElementById("head1");
   head1.firstChild.nodeValue=newtitle;
}
</script>
</head>
<body>
<h1 ID="head1">Dynamic Text in JavaScript</h1>
<p>Using the W3C DOM, you can dynamically
change the heading at the top of this
page. Enter a new title and click the
Change button.</p>
<form name="form1">
<input type="text" name="newtitle" size="25">
<input type="button" value="Change!"
  onClick="ChangeTitle()">
</form>
</body>
</html>

This example defines a form that allows the user to enter a new heading for the page. Pressing the button calls the ChangeTitle function, defined in the header. This function gets the value the user entered in the form, and changes the heading's value to the new text.

Figure 20.2 shows this page in action in Internet Explorer 6, after a new title has been entered and the Change button has been clicked.

20fig02.jpg

Figure 20.2 The heading-changing example in action.

Share ThisShare This

Informit Network