• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

14. Creating Dynamic Content > 14.10. Creating Text Content for a New Element

Creating Text Content for a New Element

NN 6, IE 5

Problem

You want to use scripts to generate a portion of body content after the page loads.

Solution

Use the W3C DOM text node-creation method of the document object. The sole parameter is the string of text content destined for an element container:

var txt = document.createTextNode("My dog has fleas.");

You can now append or insert this text node as a new child node of any element node, including an element node that has been created but not yet inserted into the document tree.

Discussion

A typical sequence for creating both a new element and its text content is as follows:

var elem = document.createElement("p");
var txt = document.createTextNode("My dog has fleas.");
elem.appendChild(txt);
document.body.appendChild(elem);

PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint