XML DOM appendChild() 方法

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 对象
计算机