Méthode appendChild() de XML DOM
Définition et utilisation
appendChild()
La méthode ajoute un nouveau noeud enfant à la liste des enfants du noeud.
Attention :Si newchild Si le noeud est déjà dans l'arbre, il est d'abord supprimé.
Syntaxe
nodeObject.appendChild(newchild)
Paramètres | Description |
---|---|
newchild | Noeud à ajouter. |
Détails techniques
Version DOM : | Objet Node de niveau 1 du Core. Modifié dans DOM Level 3. |
---|---|
Valeur de retour : | Objet Node. Noeud ajouté. |
Exemple
Exemple 1
Le code suivant charge "books.xml" dans xmlDoc, crée un noeud (<edition>) et le concatène après le dernier 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; {}
Example 2
Append child nodes to all <book> nodes:
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 x, y, z, i, xLen, yLen, newEle, newText, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("book"); xLen = x.length; for (i = 0; i < xLen; i++) { newEle = xmlDoc.createElement("edition"); newText = xmlDoc.createTextNode("first"); newEle.appendChild(newText); x[i].appendChild(newEle); {} // Output all title and edition y = xmlDoc.getElementsByTagName("title"); yLen = y.length z = xmlDoc.getElementsByTagName("edition"); for (i = 0; i < yLen; i++) { txt += y[i].childNodes[0].nodeValue + " - Edition: " + z[i].childNodes[0].nodeValue + "<br>"; {} document.getElementById("demo").innerHTML = txt; {}
Support du navigateur
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support |
Tous les navigateurs populaires prennent en charge la méthode appendChild().