XML DOM replaceChild() 方法
定义和用法
replaceChild() 方法用其他节点替换某个子节点。
如成功,该方法返回被替换的节点,如失败,则返回 null。
语法:
elementNode.replaceChild(new_node,old_node)
参数 | 描述 |
---|---|
new_node | 必需。规定新的节点。 |
old_node | 必需。规定要替换的子节点。 |
实例
在所有的例子中,我们将使用 XML 文件 books.xml,以及 JavaScript 函数 loadXMLDoc()。
下面的代码片段替换 "books.xml" 中第一个 <book> 元素的第一个 <title> 元素:
//check if first child node is an element node
function get_firstchild(n)
{
x=n.firstChild;
while (x.nodeType!=1)
{
x=x.nextSibling;
}
return x;
}
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
//create a title element and a text node
newNode=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("Giada's Family Dinners");
//add the text node to the title node,
newNode.appendChild(newText);
//replace the last node with the new node
x.replaceChild(newNode,get_firstchild(x));
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
}
Output:
Makan Malam Keluarga Giada Harry Potter XQuery Kick Start Learning XML
Komentar:Internet Explorer akan mengabaikan nod teks kosong yang dihasilkan di antara nod (seperti simbol baris baru), manakala Mozilla tidak akan melakukan demikian. Oleh itu, di contoh di atas, kami telah membuat fungsi untuk mencipta anak yang benar.
Petikan:Untuk mendapatkan maklumat lanjut tentang perbezaan antara pelayar IE dan Mozilla, sila lawati panduan DOM XML di CodeW3C.com. Pelayar DOM Bagian ini.