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 />");
}

輸出:

Giada's Family Dinners
Harry Potter
XQuery Kick Start
Learning XML

注釋:Internet Explorer 會忽略節點間生成的空白文本節點(例如,換行符號),而 Mozilla 不會這樣做。因此,在上面的例子中,我們創建了一個函數來創建正確的子元素。

提示:如需更多有關 IE 與 Mozilla 瀏覽器差異的內容,請訪問 CodeW3C.com 的 XML DOM 教程中的 DOM 瀏覽器 這一節。