Phương pháp XML DOM replaceChild()

Định nghĩa và cách sử dụng

replaceChild() Phương pháp sử dụng node mới để thay thế con node.

Node mới có thể là node hiện có trong tài liệu hoặc có thể tạo mới.

Lưu ý:Con node bị thay thế có thể được chèn vào bất kỳ phần tử nào trong cùng một tài liệu sau này. Hãy sử dụng phương pháp insertBefore() hoặc appendChild() để chèn vào cùng một tài liệu sau này, hoặc sử dụng phương pháp adoptNode() hoặc importNode() để chèn node thay thế vào một tài liệu khác.

Cú pháp

nodeObject.replaceChild(newchild,oldchild)

Tham số

Tham số Mô tả
newchild Bắt buộc. Đối tượng Node. Đối tượng node mới cần được thêm vào danh sách con của node con.
oldchild Bắt buộc. Đối tượng Node. Đối tượng node sẽ được thay thế trong danh sách con của node con.

Chi tiết kỹ thuật

Phiên bản DOM: Core Level 1 Node Object. Được sửa đổi trong DOM Level 3.
返回值: Node 对象。被替换的节点(oldchild)。

实例

下面的代码将 "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;
}

Thử ngay

Hỗ trợ trình duyệt

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Hỗ trợ Hỗ trợ Hỗ trợ Hỗ trợ Hỗ trợ

Tất cả các trình duyệt phổ biến đều hỗ trợ replaceChild() Phương thức.