appendChild() 方法把新的子节点追加到节点的子节点列表的末尾。
该方法返回新的子节点。
appendChild(newchild)
| 参数 | 描述 |
|---|---|
| newchild | 要追加的节点。 |
下面的代码片段使用 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
appendChild() - 向所有的 <book> 节点追加一个子节点
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
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);
}
//Output all titles and editions
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>");
}
</script>
</body>
</html>