THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

XML DOM appendChild() Method


Element Object Reference Element Object

Example

The following code fragment loads "books.xml" into xmlDoc and creates a node (<edition>), and appends it after the last child of the first <book> node:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
��� if (xhttp.readyState == 4 && xhttp.status == 200) {
������� myFunction(xhttp);
��� }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var newel = xmlDoc.createElement("edition");
    var x = xmlDoc.getElementsByTagName("book")[0];
    x.appendChild(newel);
    document.getElementById("demo").innerHTML =
    x.getElementsByTagName("edition")[0].nodeName;
}

The output of the code above will be:

edition
Try it yourself »

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 append

Example

The following code fragment loads "books.xml" into xmlDoc and appends a new node to all <book> elements:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
��� if (xhttp.readyState == 4 && xhttp.status == 200) {
������� myFunction(xhttp);
��� }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
    var x, y, z, i, newel, newtext, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book");
    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++) {
        txt += y[i].childNodes[0].nodeValue +
        " - Edition: " +
        z[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

The output of the code above will be:

Everyday Italian - Edition: First
Harry Potter - Edition: First
XQuery Kick Start - Edition: First
Learning XML - Edition: First
Try it yourself »

Element Object Reference Element Object