Méthode XML DOM appendChild()

Définition et utilisation

appendChild() La méthode ajoute un noeud après le dernier noeud enfant d'un élément de noeud spécifié.

Cette méthode retourne le noeud enfant nouveau.

Grammaire

appendChild(noeud)
Paramètre Description
noeud Obligatoire. Le noeud à ajouter.

Exemple

Exemple 1

Le code suivant charge "books.xml" dans xmlDoc, crée un noeud (<edition>) et le追加 au dernier noeud enfant du premier noeud <book> :

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   {}
};
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;
{}

Essayez-le vous-même

Exemple 2

Le code suivant charge "books.xml" dans xmlDoc et ajoute de nouveaux nœuds à tous les éléments <book> :

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);
    {}
    // Afficher tous les title et edition
    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;
{}

Essayez-le vous-même