XML DOM replaceChild() 方法
定義和用法
replaceChild() 方法用其他節(jié)點(diǎn)替換某個(gè)子節(jié)點(diǎn)。
如成功,該方法返回被替換的節(jié)點(diǎn),如失敗,則返回 null。
語法:
elementNode.replaceChild(new_node,old_node)
參數(shù) | 描述 |
---|---|
new_node | 必需。規(guī)定新的節(jié)點(diǎn)。 |
old_node | 必需。規(guī)定要替換的子節(jié)點(diǎn)。 |
實(shí)例
在所有的例子中,我們將使用 XML 文件 books.xml,以及 JavaScript 函數(shù) loadXMLDoc()。
下面的代碼片段替換 "books.xml" 中第一個(gè) <book> 元素的第一個(gè) <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 />");
}
輸出:
Giada's Family Dinners Harry Potter XQuery Kick Start Learning XML
注釋:Internet Explorer 會(huì)忽略節(jié)點(diǎn)間生成的空白文本節(jié)點(diǎn)(例如,換行符號(hào)),而 Mozilla 不會(huì)這樣做。因此,在上面的例子中,我們創(chuàng)建了一個(gè)函數(shù)來創(chuàng)建正確的子元素。
提示:如需更多有關(guān) IE 與 Mozilla 瀏覽器差異的內(nèi)容,請(qǐng)?jiān)L問 W3School 的 XML DOM 教程中的 DOM 瀏覽器 這一節(jié)。