XML DOM appendChild() method
Definition and Usage
The appendChild() method adds a node after the last child node of the specified element node.
This method returns the new child node.
Syntax:
appendChild(node)
Parameter | Description |
---|---|
node | Required. The node to be appended. |
Example
In all examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().
The following code snippet creates and appends a node to the first <book> element, and then outputs all child nodes of the first <book> element:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
var newel,newtext;
for (i=0;i<x.length;i++)
{
newel=xmlDoc.createElement('edition');
newtext=xmlDoc.createTextNode('First');
newel.appendChild(newtext);
x[i].appendChild(newel);
}
//Output all titles and editions
y=xmlDoc.getElementsByTagName("title");
z=xmlDoc.getElementsByTagName("edition");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write(" - Edizione: ");
document.write(z[i].childNodes[0].nodeValue);
document.write("<br />");
}
Output del codice sopra:
Everyday Italian - Edizione: Prima Harry Potter - Edizione: Prima XQuery Kick Start - Edizione: Prima Learning XML - Edizione: Prima
Nota:Internet Explorer ignora i nodi di testo vuoti generati tra i nodi (ad esempio, i caratteri di ritorno a capo), mentre Mozilla non lo fa. Pertanto, nell'esempio sopra, trattiamo solo i nodi elemento (nodeType dell'elemento uguale a 1).
Per ulteriori informazioni sulle differenze tra IE e Mozilla, visita il tutorial XML DOM su CodeW3C.com Browser DOM Questa sezione.