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 对象。被替换的节点(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;
}

亲自试一试

浏览器支持

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
支持 支持 支持 支持 支持

所有主流浏览器都支持 replaceChild() 方法。