XML DOM appendChild() 方法
定義和用法
appendChild() 方法可向節(jié)點(diǎn)的子節(jié)點(diǎn)列表的末尾添加新的子節(jié)點(diǎn)。
此方法可返回這個新的子節(jié)點(diǎn)。
語法:
appendChild(newchild)
| 參數(shù) | 描述 |
|---|---|
| newchild | 所添加的節(jié)點(diǎn) |
返回值
加入的節(jié)點(diǎn)。
描述
該方法將把節(jié)點(diǎn) newchild 添加到文檔中,使它成為當(dāng)前節(jié)點(diǎn)的最后一個子節(jié)點(diǎn)。
如果文檔樹中已經(jīng)存在了 newchild,它將從文檔樹中刪除,然后重新插入它的新位置。如果 newchild 是 DocumentFragment 節(jié)點(diǎn),則不會直接插入它,而是把它的子節(jié)點(diǎn)按序插入當(dāng)前節(jié)點(diǎn)的 childNodes[] 數(shù)組的末尾。
注意,來自一個文檔的節(jié)點(diǎn)(或由一個文檔創(chuàng)建的節(jié)點(diǎn))不能插入另一個文檔。也就是說,newchild 的 ownerDocument 屬性必須與當(dāng)前節(jié)點(diǎn)的 ownerDocument 屬性相同。
例子
下面的函數(shù)將在文檔末尾插入一個新段:
function appendMessage (message) {
var pElement = document.createElement("p");
var messageNode = document.createTextNode(message);
pElement.appendChild(messageNode);
document.body.appendChild(pElement);
}
實(shí)例
在所有的例子中,我們將使用 XML 文件 books.xml,以及 JavaScript 函數(shù) loadXMLDoc()。
下面的代碼片段可創(chuàng)建并向首個 <book> 元素添加一個節(jié)點(diǎn),然后輸出首個 <book> 元素的所有子節(jié)點(diǎn):
xmlDoc=loadXMLDoc("books.xml");
var newel=xmlDoc.createElement('edition');
var newtext=xmlDoc.createTextNode('First');
newel.appendChild(newtext);
var x=xmlDoc.getElementsByTagName('book')[0];
x.appendChild(newel);
var y=x.childNodes;
for (var i=0;i<y.length;i++)
{
//Display only element nodes
if (y[i].nodeType==1)
{
document.write(y[i].nodeName);
document.write("<br />");
}
}
輸出:
title author year price edition
注釋:Internet Explorer 會忽略節(jié)點(diǎn)間生成的空白文本節(jié)點(diǎn)(例如,換行符號),而 Mozilla 不會這樣做。因此,在下面的例子中,我們僅處理元素節(jié)點(diǎn)(元素節(jié)點(diǎn)的 nodeType=1)。
提示:如需更多有關(guān) IE 與 Mozilla 瀏覽器之間 XML DOM 的差異的內(nèi)容,請?jiān)L問我們的 DOM 瀏覽器 章節(jié)。