XML DOM replaceChild() メソッド

定義と用法

replaceChild()} 이 메서드는 하나의 자식 노드를 다른 자식 노드로 대체합니다。

성공 시, 이 함수는 대체된 노드를 반환하고 실패 시 NULL

문법

elementNode.replaceChild(new_node,old_node)
파라미터 설명
new_node 필수. 새 노드를 정의합니다.
old_node 필수. 대체할 자식 노드를 정의합니다.

예제

아래의 코드는 "books.xml"를 xmlDoc에 로드하고 첫 번째 <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, newNode, newTitle, newText, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.documentElement;
    // book 요소, title 요소 및 텍스트 노드를 생성합니다
    newNode = xmlDoc.createElement("book");
    newTitle = xmlDoc.createElement("title");
    newText = xmlDoc.createTextNode("Hello World");
    // title 요소에 텍스트 노드를 추가합니다
    newTitle.appendChild(newText);
    // 이 title 요소를 book 요소에 추가합니다
    newNode.appendChild(newTitle);
    y = xmlDoc.getElementsByTagName("book")[0];
    // 이 새로운 book 요소를 첫 번째 book 요소로 대체합니다
    x.replaceChild(newNode, y);
    z = xmlDoc.getElementsByTagName("title");
    // 모든 title 출력
    for (i = 0; i < z.length; i++) {
        txt += z[i].childNodes[0].nodeValue + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

직접 시험해 보세요