Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Adding Text to a Page

Next, you can create a script that actually adds text to a page. To do this, you must first create a new text node. This statement creates a new text node with the text "this is a test":

var node=document.createTextNode("this is a test");

Next, you can add this node to the document. To do this, you use the appendChild method. The text can be added to any element that can contain text, but we will use a paragraph. The following statement adds the text node defined above to the paragraph with the identifier p1:

document.getElementById("p1").appendChild(node);

Listing 20.3 shows the HTML document for a complete example that uses this technique, using a form to allow the user to specify text to add to the page.

Example 20.3. Adding Text to a Page

<html>
<head>
<title>Adding to a page</title>
<script language="Javascript" type="text/javascript">
function AddText() {
   var sentence=document.form1.sentence.value;
   var node=document.createTextNode(" " + sentence);
   document.getElementById("p1").appendChild(node);
}
</script>
</head>
<body>
<h1>Create Your Own Content</h1>
<p ID="p1">Using the W3C DOM, you can dynamically
add sentences to this paragraph. Type a sentence
and click the Add button.</p>
<form name="form1">
<input type="text" name="sentence" size="65">
<input type="button" value="Add" onClick="AddText()">
</form>
</body>
</html>

In this example, the <p> section defines the paragraph that will hold the added text. The <form> section defines a form with a text field called sentence and an add button, which calls the AddText function. This function is defined in the header.

The AddText function first assigns the sentence variable to the text typed in the text field. Next, it creates a new text node containing the sentence, and appends the new text node to the paragraph.

Load this document into a browser to test it, and try adding several sentences by typing them and clicking the Add button. Figure 20.3 shows Netscape 6's display of this document after several sentences have been added to the paragraph.

20fig03.jpg

Figure 20.3 Netscape 6 shows the text-adding example.

Share ThisShare This

Informit Network