XML DOM replaceChild() 메서드

정의와 사용법

replaceChild() 메서드는 새 노드로 자식 노드를 대체합니다.

새 노드는 문서에 존재하는 기존 노드일 수도 있고, 새 노드를 생성할 수도 있습니다.

ヒント:대체된 자식 노드는 나중에 같은 문서의 어떤 요소에도 삽입할 수 있습니다. 나중에 같은 문서에 삽입하려면 insertBefore() 또는 appendChild() 메서드를 사용하거나, 대체된 노드를 다른 문서에 삽입하려면 adoptNode() 또는 importNode() 메서드를 사용하세요.

문법

nodeObject.replaceChild(newchild,oldchild)

파라미터

파라미터 설명
newchild 必需. Node 객체. 자식 노드 목록에 삽입할 새 노드.
oldchild 必需. Node 객체. 자식 노드 목록에서 대체될 노드.

기술 세부 사항

DOM 버전: Core Level 1 Node Object. DOM Level 3에서 수정.
반환 값: Node 객체. 대체된 노드(olderchild).

예제

아래 코드는 "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;
}

직접 시험해 보세요

브라우저 지원

크롬 에지 파이어폭스 사파리 오퍼라
크롬 에지 파이어폭스 사파리 오퍼라
지원 지원 지원 지원 지원

모든 주요 브라우저가 지원합니다 replaceChild() 메서드.