HTML and CSS Reference
In-Depth Information
Once a node has been created, it must be attached to a node existing in the document to
become part of the document. Unattached nodes and node trees are known as document
fragments and exist only in a browser's memory. They are not rendered on the Web page,
although you can still access document fragments and work with them in your programs.
Figure 14-12 describes several methods for attaching one node to another.
Figure 14-12
Methods to add and remove nodes
node .appendChild( new )
Appends the node new as a new child of node
node .insertBefore( new , child )
Inserts the child node new as a new child of node , placing it
before the specified child node; if child is omitted, the new
node is inserted as the last child node
node .normalize()
Traverses all child nodes of node ; any adjacent text nodes are
merged into a single text node
node .removeChild( old )
Removes the child node old from node
When applied to a node
that already exists, the
appendChild() and
insertBefore() methods
move the node from its
current location to its new
node .replaceChild( new , old )
Replaces the child node old with the child node new
Using the properties and methods described in Figures 14-10 and 14-12, you can create
elaborate document fragments that contain several levels of different nodes. Figure 14-13
describes the process by which you would create the following HTML fragment using
those methods:
<p><em>Historic</em> Documents</p>
Figure 14-13
creating a document fragment
Node Tree
newEM = document.createElement("em");
text1 = document.createTextNode("Historic");
newP = document.createElement("p");
text2 = document.createTextNode(" Documents");
The approach shown in Figure 14-13 first uses the createElement() and
createTextNode() methods to create four nodes: an element node for a paragraph,
an element node for emphasized text, a text node containing the text string Historic ,
and a text node containing a blank space followed by the text string Documents . The
appendChild() method is then employed to attach the text nodes to the element nodes.
Search WWH ::

Custom Search