XML DOM appendChild() method
Definition and usage
The appendChild() method can add a new child node to the end of the child node list of a node.
This method returns this new child node.
Syntax:
appendChild(newchild)
Parameter | Description |
---|---|
newchild | The node added |
Return value
The node added.
Description
This method adds the node newchild to the document, making it the last child node of the current node.
If newchild already exists in the document tree, it will be removed from the document tree and then reinserted at its new location. If newchild is a DocumentFragment node, it will not be inserted directly, but its child nodes will be inserted in order at the end of the childNodes[] array of the current node.
Note that a node from one document (or a node created by one document) cannot be inserted into another document. That is, the ownerDocument property of newchild must be the same as the ownerDocument property of the current node.
Example
The following function inserts a new paragraph at the end of the document:
function appendMessage (message) { var pElement = document.createElement("p"); var messageNode = document.createTextNode(message);pElement.appendChild(messageNode);
document.body.appendChild(pElement);
}
Example
In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
The following code snippet creates and adds a node to the first <book> element, and then outputs all child nodes of the first <book> element:
xmlDoc=loadXMLDoc("books.xml");
var newel=xmlDoc.createElement('edition');
var newtext=xmlDoc.createTextNode('First');
newel.appendChild(newtext);
var x=xmlDoc.getElementsByTagName('book')[0];
x.appendChild(newel);
;
var y=x.childNodes;
for (var i=0;i<y.length;i++)
{
//Display only element nodes
if (y[i].nodeType==1)
{
document.write(y[i].nodeName);
document.write("<br />");
}
}
Output:
title author year price edition
Note:Internet Explorer will ignore the generated whitespace text nodes between nodes (such as newline symbols), while Mozilla will not do so. Therefore, in the following example, we only handle element nodes (element nodes have nodeType=1).
Tip:For more information about the differences between XML DOM in IE and Mozilla browsers, please visit our DOM Browser Chapter.