- Refresher on the Different Types of Scripting
- Displaying Random Content on the Client Side
- Understanding the Document Object Model
- Using window Objects
- Working with the document Object
- Accessing Browser History
- Working with the location Object
- More About the DOM Structure
- Working with DOM Nodes
- Creating Positionable Elements (Layers)
- Hiding and Showing Objects
- Modifying Text Within a Page
- Adding Text to a Page
- Changing Images Based on User Interaction
- Thinking Ahead to Developing HTML5 Applications
- Summary
- Q & A
- Workshop
Adding Text to a Page
You can create a script that actually adds text to a page rather than just changing existing text. 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 into the document. To do this, you use the appendChild method. The text can be added to any element that can contain text, but in this example we will just use a paragraph. The following statement adds the text node defined previously to the paragraph with the identifier paragraph1:
document.getElementById("paragraph1").appendChild(node);
Listing 6.9 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.
LISTING 6.9 Adding Text to a Page
<!DOCTYPE html> <html lang="en"> <head> <title>Adding Text to a Page</title> <script type="text/javascript"> function addText() { if (!document.getElementById) return; var sentence=document.changeform.sentence.value; var node=document.createTextNode(" " + sentence); document.getElementById("paragraph1").appendChild(node); document.changeform.sentence.value=""; } </script> </head> <body> <h1 id="heading1">Create Your Own Content</h1> <p id="paragraph1"> Using the W3C DOM, you can dynamically add sentences to this paragraph.</p> <p>Type a sentence and click the Add! button.</p> <form name="changeform"> <input type="text" name="sentence" size="65" /> <button type="button" onclick="addText();">Add!</button> </form> </body> </html>
In this example, the <p> element with the ID of paragraph1 is the paragraph that will hold the added text. The <form> element is a form with a text field called sentence and an Add! button that calls the addText() function when clicked. This JavaScript function is defined in the <script> tag in the <head> element. The addText() function first assigns text typed in the text field to the sentence variable. Next, the script creates a new text node containing the value of the sentence variable and then 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 6.10 shows this document after several sentences have been added to the paragraph.
FIGURE 6.10 The text-addition example in action.