XML DOM replaceChild() メソッド
定義と用法
replaceChild()
メソッドは子ノードを別の子ノードに置き換えます。
成功時には、この関数は置き換えられたノードを返し、失敗時には NULL
。
文法
elementNode.replaceChild(new_node,old_node)
パラメータ | 説明 |
---|---|
new_node | 必須。新しいノードを指定します。 |
old_node | 必須。置き換える子ノードを指定します。 |
例
以下のコードは "books.xml" を xmlDoc にロードし、最初の <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; // book 要素、title 要素、テキストノードを生成します newNode = xmlDoc.createElement("book"); newTitle = xmlDoc.createElement("title"); newText = xmlDoc.createTextNode("Hello World"); // title ノードにテキストノードを追加します newTitle.appendChild(newText); // この title ノードを book ノードに追加します newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("book")[0]; // この新しい book ノードを使用して最初の book ノードを置き換えます x.replaceChild(newNode, y); z = xmlDoc.getElementsByTagName("title"); // 全ての title を出力する for (i = 0; i < z.length; i++) { txt += z[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; }