Méthode replaceChild() de XML DOM
Définition et utilisation
replaceChild()
Cette méthode remplace un sous-nœud par un autre sous-nœud.
En cas de succès, cette fonction retourne le nœud remplacé, en cas d'échec, elle retourne NULL
.
Syntaxe
elementNode.replaceChild(new_node,old_node)
Paramètres | Description |
---|---|
new_node | Obligatoire. Définit le nouveau nœud. |
old_node | Obligatoire. Définit le sous-nœud à remplacer. |
Exemple
Le code suivant charge "books.xml" dans xmlDoc et remplace le premier élément <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 x, y, z, i, newNode, newTitle, newText, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.documentElement; // Créez un élément book, un élément title et un noeud texte newNode = xmlDoc.createElement("book"); newTitle = xmlDoc.createElement("title"); newText = xmlDoc.createTextNode("Hello World"); // Ajoutez un noeud texte à ce noeud title newTitle.appendChild(newText); // Ajoutez ce noeud title au noeud book newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("book")[0]; // Utilisez ce nouveau noeud book pour remplacer le premier noeud book x.replaceChild(newNode, y); z = xmlDoc.getElementsByTagName("title"); // Afficher tous les title for (i = 0; i < z.length; i++) { txt += z[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; }