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, as well as 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(" - Edición: ");
document.write(z[i].childNodes[0].nodeValue);
document.write("<br />");
}

La salida del código anterior es:

Everyday Italian - Edición: Primera
Harry Potter - Edición: Primera
XQuery Kick Start - Edición: Primera
Learning XML - Edición: Primera

Nota:Internet Explorer ignorará los nodos de texto en blanco generados entre los nodos (como caracteres de nueva línea), mientras que Mozilla no lo hace. Por lo tanto, en el ejemplo anterior, solo se procesan los nodos de elemento (los nodos de elemento tienen nodeType igual a 1).

Para obtener más información sobre las diferencias entre Internet Explorer y el navegador Mozilla, visita el tutorial de XML DOM en CodeW3C.com Navegador DOM Esta sección.