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 + 
        「 - 版本: 」 + 
        z[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

自分で試してみる

ブラウザサポート

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
サポート サポート サポート サポート サポート

すべての主要ブラウザが appendChild() メソッドをサポートしています。