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;
}

직접 시험해 보세요