- 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
- Q & A
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:
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
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.