XML DOM appendChild() 方法


Element 對象參考手冊 Element 對象

定義和用法

appendChild() 方法在指定元素節點的最後一個子節點後添加節點。

該方法返回新的子節點。

語法

appendChild(node)

參數 描述
node 必需。要追加的節點。


實例 1

下麵的代碼片段使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中,創建節點(<edition>),並把它添加到第一個 <book> 元素的最後一個子節點的後面:

實例

xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

document.write(x.getElementsByTagName("edition")[0].nodeName);

輸出:

edition


實例 2

下麵的代碼片段使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中,並向所有的 <book> 元素追加一個新的節點:

實例

xmlDoc=loadXMLDoc("books.xml"); x=xmlDoc.getElementsByTagName("book"); for (i=0;i<x.length;i++) { newel=xmlDoc.createElement("edition"); newtext=xmlDoc.createTextNode("first"); newel.appendChild(newtext); x[i].appendChild(newel); } // 輸出所有 title 和 edition y=xmlDoc.getElementsByTagName("title"); z=xmlDoc.getElementsByTagName("edition"); for (i=0;i<y.length;i++) { document.write(y[i].childNodes[0].nodeValue); document.write(" - Edition: "); document.write(z[i].childNodes[0].nodeValue); document.write("<br>"); }

輸出:

Everyday Italian - Edition: First
Harry Potter - Edition: First
XQuery Kick Start - Edition: First
Learning XML - Edition: First


Element 對象參考手冊 Element 對象