XML DOM replaceChild() 메서드
❮ 노드 객체
예시
다음 코드 조각은 " 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;
// Create a book
element, title element and a text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A
Notebook");
// Add a text node to the title node
newTitle.appendChild(newText);
// Add the title node to the book node
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
// Replace the first book node with the new book node
x.replaceChild(newNode,
y);
z = xmlDoc.getElementsByTagName("title");
// Output all titles
for (i = 0; i < z.length; i++) {
txt += z[i].childNodes[0].nodeValue
+ "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
위 코드의 출력은 다음과 같습니다.
A Notebook
Harry Potter
XQuery Kick Start
Learning XML
정의 및 사용
replaceChild() 메서드는 자식 노드를 새 노드로 바꿉니다.
새 노드는 문서의 기존 노드이거나 새 노드를 만들 수 있습니다.
팁: 교체된 자식 노드는 나중에 같은 문서의 모든 요소에 삽입할 수 있습니다. insertBefore() 또는 appendChild() 메소드를 사용 하여 나중에 동일한 문서에 삽입하거나, acceptNode() 또는 importNode() 메소드를 사용하여 교체된 노드를 다른 문서에 삽입하십시오.
브라우저 지원
replaceChild() 메서드는 모든 주요 브라우저에서 지원됩니다.
통사론
nodeObject.replaceChild(newchild,oldchild)
매개변수
Parameter | Type | Description |
---|---|---|
newchild | Node object | Required. The new node to put in the child list |
oldchild | Node object | Required. The node that will be replaced in the child list |
반환 값
Type | Description |
---|---|
Node object | The replaced node (oldchild) |
기술적 세부 사항
DOM 버전 | 코어 레벨 1 노드 개체. DOM 레벨 3에서 수정됨 |
---|
❮ 노드 객체