XML DOM appendChild() 方法
定义和用法
appendChild() 方法在指定元素节点的最后一个子节点之后添加节点。
该方法返回新的子节点。
语法
appendChild(node)
| 参数 | 描述 |
|---|---|
| node | 必需。要追加的节点。 |
实例
例子 1
下面的代码将 "books.xml" 加载到 xmlDoc 中,并创建一个节点 (<edition>),然后将其追加到第一个 <book> 节点的最后一个子节点之后:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var newel = xmlDoc.createElement("edition");
var x = xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
document.getElementById("demo").innerHTML =
x.getElementsByTagName("edition")[0].nodeName;
}
例子 2
下面的代码将 "books.xml" 加载到 xmlDoc 中,并将新节点追加到所有 <book> 元素:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, y, z, i, newel, newtext, xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
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++) {
txt += y[i].childNodes[0].nodeValue +
" - Edition: " +
z[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}