XML DOM appendChild() 方法

定義和用法

appendChild() 方法將新的子節點追加到節點的子節點列表的末尾。

注意:如果 newchild 已經在樹中,則首先將其刪除。

語法

nodeObject.appendChild(newchild)
參數 描述
newchild 要添加的節點。

技術細節

DOM 版本: Core Level 1 Node Object。在 DOM Level 3 中修改。
返回值: 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

將子節點追加到所有 <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 x, y, z, i, xLen, yLen, newEle, newText, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book");
    xLen = x.length;
    for (i = 0; i < xLen; i++) { 
        newEle = xmlDoc.createElement("edition");
        newText = xmlDoc.createTextNode("first");
        newEle.appendChild(newText);
        x[i].appendChild(newEle);
    }
    // 輸出所有 title 和 edition
    y = xmlDoc.getElementsByTagName("title");
    yLen = y.length
    z = xmlDoc.getElementsByTagName("edition");
    for (i = 0; i < yLen; i++) { 
        txt += y[i].childNodes[0].nodeValue + 
        " - Edition: " + 
        z[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

親自試一試

瀏覽器支持

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
支持 支持 支持 支持 支持

所有主流瀏覽器都支持 appendChild() 方法。