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() 메서드를 지원합니다.