XML DOM appendChild() 方法
❮ 元素物件
示例
下面的程式碼片段載入 "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;
}
上面程式碼的輸出將是
edition
自己動手試一試 »
定義和用法
appendChild() 方法將一個節點新增到指定元素節點的最後一個子節點之後。
此方法返回新建立的子節點。
語法
appendChild(node)
引數 | 描述 |
---|---|
node | 必需。要新增的節點。 |
示例
下面的程式碼片段載入 "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);
}
// 輸出所有標題和版本
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;
}
上面程式碼的輸出將是
Everyday Italian - Edition: First
Harry Potter - Edition: First
XQuery Kick Start - Edition: First
Learning XML - Edition: First
自己動手試一試 »
❮ 元素物件