XML DOM replaceChild()メソッド
❮ノードオブジェクト
例
次のコードフラグメントは、「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;
// Create a book
element, title element and a text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A
Notebook");
// Add a text node to the title node
newTitle.appendChild(newText);
// Add the title node to the book node
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
// Replace the first book node with the new book node
x.replaceChild(newNode,
y);
z = xmlDoc.getElementsByTagName("title");
// Output all titles
for (i = 0; i < z.length; i++) {
txt += z[i].childNodes[0].nodeValue
+ "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
上記のコードの出力は次のようになります。
A Notebook
Harry Potter
XQuery Kick Start
Learning XML
定義と使用法
replaceChild()メソッドは、子ノードを新しいノードに置き換えます。
新しいノードは、ドキュメント内の既存のノードである可能性があります。または、新しいノードを作成することもできます。
ヒント:置き換えられた子ノードは、後で同じドキュメント内の任意の要素に挿入できます。 insertBefore()またはappendChild()メソッドを使用 して、後で同じドキュメントに挿入するか、adoptNode()またはimportNode()メソッドを使用して、置き換えられたノードを別のドキュメントに挿入します。
ブラウザのサポート
replaceChild()メソッドは、すべての主要なブラウザーでサポートされています。
構文
nodeObject.replaceChild(newchild,oldchild)
パラメーター
Parameter | Type | Description |
---|---|---|
newchild | Node object | Required. The new node to put in the child list |
oldchild | Node object | Required. The node that will be replaced in the child list |
戻り値
Type | Description |
---|---|
Node object | The replaced node (oldchild) |
技術的な詳細
DOMバージョン | コアレベル1ノードオブジェクト。DOMレベル3で変更 |
---|
❮ノードオブジェクト