Table of Contents

XML.appendChild( ) Method Flash 5

add a new child node to a node, or move an existing node
theNode.appendChild(childNode)

Arguments

childNode

An existing XML node object.

Description

The appendChild( ) method adds the specified childNode to theNode as theNode's last child, where theNode can be an XML or XMLnode instance. We can use appendChild( ) to add a new node to an existing node, to move a node within a document, or to move a node between documents. In each of these cases, childNode must be a reference to a node object that already exists.

To add a new child node to an existing node, we must first create the new child node using createElement( ), createTextNode( ), or cloneNode( ) or by parsing XML source code into an XML object. For example, in the following code, we create a new P node and a new text node. We append the text node to the P node and then append the P node and its text node child to the top node of a document:

// Create a document
myDoc = new XML('<P>paragraph 1</P>');
   
// Create a P node and a text node
newP = myDoc.createElement("P");
newText = myDoc.createTextNode("paragraph 2");
   
// Append the text node to the P node
newP.appendChild(newText);
   
// Append the P node (including its text child) to myDoc
myDoc.appendChild(newP);
   
trace(myDoc);  // Displays: "<P>paragraph 1</P><P>paragraph 2</P>"

To move a node within a document, specify a childNode that is a reference to an existing node in the document. In this situation, childNode indicates the old location of the node and theNode indicates the new parent of the node. In the process of being appended to theNode, childNode is removed from its previous parent node. For example, here we move the B node from its parent P node to the root of the document:

// Create a new document
myDoc = new XML('<P>paragraph 1<B>bold text</B></P>');
   
// Store a reference to the B node
boldText = myDoc.firstChild.childNodes[1];
   
// Append the B node to the root of the document, while removing it from P
myDoc.appendChild(boldText);
   
trace(myDoc);  // Displays: "<P>paragraph 1</P><B>bold text</B>"

We also could have skipped the reference-storing step and just moved the node directly:

myDoc.appendChild(myDoc.firstChild.childNodes[1]);

To move a node between documents, childNode should be a reference to a node in the first (source) document and theNode should be a reference to a node in the second (target) document. For example, here we move the B node from myDoc to myOtherDoc:

myDoc = new XML('<P>paragraph 1<B>bold text</B></P>');
myOtherDoc = new XML();
   
myOtherDoc.appendChild(myDoc.firstChild.childNodes[1]);
   
trace(myDoc);       // Displays: "<P>paragraph 1</P>"
trace(myOtherDoc);  // Displays: "<B>bold text</B>"

See Also

XML.cloneNode( ), XML.createElement( ), XML.createTextNode( ), XML.insertBefore( ), XML.removeNode( )


Table of Contents