XML DOM 替换节点

XML DOM 替换节点 最全速查表(2025 版)

—— 3 秒知道用哪个方法,99% 的需求全在这张表里!

替换方式推荐指数写法(2025 首选)适用场景是否最简洁
自己替换自己(最现代)★★★★★oldNode.replaceWith(newNode)任意节点替换,2025 年必会!最简洁
让爸爸替换孩子(经典老写法)★★★★★parent.replaceChild(newNode, oldNode)兼容所有老浏览器经典
替换为多个节点★★★★★oldNode.replaceWith(node1, node2, ...)一个节点换成好几个超强
替换为纯文本★★★★★oldNode.replaceWith("纯文本")把标签换成文字(比如去掉 )一行搞定
批量替换★★★★★querySelectorAll(...).forEach(old => old.replaceWith(new))批量统一替换优雅

真实 XML 示例(全程用这一个)

<bookstore>
  <book id="1">
    <title>JavaScript 高级程序设计</title>
    <author>扎卡斯</author>
    <price>99.00</price>
  </book>
  <book id="2">
    <title>三体</title>
    <author>刘慈欣</author>
  </book>
</bookstore>

实战代码(直接复制,全都能用)

const doc  = new DOMParser().parseFromString(xmlStr, "text/xml");
const root = doc.documentElement;

// 1. 把第一本书的 <price> 标签整个替换成纯文本(去掉标签)
const priceNode = doc.querySelector("price");
priceNode.replaceWith(priceNode.textContent);  // → 直接变成 "99.00"

// 2. 把第二本书整个替换成一本新书
const oldBook = doc.querySelector("book[id='2']");
const newBook = doc.createElement("book");
newBook.setAttribute("id", "999");
newBook.innerHTML = `<title>新书:三体全集</title><author>刘慈欣</author><price>199</price>`;

oldBook.replaceWith(newBook);

// 3. 把所有 <author> 替换成 <writer>(标签名批量改)
doc.querySelectorAll("author").forEach(author => {
  const writer = doc.createElement("writer");
  writer.textContent = author.textContent;
  author.replaceWith(writer);
});

// 4. 把某个节点替换成多个节点(超级实用!)
const title = doc.querySelector("title");
title.replaceWith(
  doc.createElement("name"),
  " by ",
  doc.createElement("writer")
);
// 结果: <name>JavaScript 高级程序设计</name> by <writer>扎卡斯</writer>

// 5. 经典老写法(兼容 IE11)
const parent = oldNode.parentNode;
parent.replaceChild(newNode, oldNode);

经典坑 & 终极解决方案

错误写法正确写法(2025)
替换后还继续用旧节点(已成“死节点”)oldNode.replaceWith(newNode); console.log(oldNode.parentNode)替换后 oldNode 脱离文档,parentNode 为 null
老浏览器不支持 replaceWith()Chrome 53+、Firefox 49+ 才支持parent.replaceChild(newNode, oldNode) 兜底
想替换成文本但传了字符串replaceWith("<b>加粗</b>")错!会变成文本节点,不是 HTML
replaceWith("纯文本")正确!字符串会被当成文本节点
批量替换时跳节点for (let node of nodes) node.replaceWith(...)正确!NodeList 是活的,但 replaceWith 安全

2025 年终极记忆口诀(背 2 句就够用一辈子)

  1. 替换节点 → 永远先用 oldNode.replaceWith(newNode)
  2. 替换多个/文本 → replaceWith(node1, "文本", node2)

终极兼容写法(支持到 IE9)

function safeReplaceWith(oldNode, newContent) {
  if (oldNode.replaceWith) {
    oldNode.replaceWith(...[].concat(newContent));
  } else {
    const parent = oldNode.parentNode;
    // 如果是多个节点
    if (Array.isArray(newContent)) {
      newContent.forEach(node => parent.insertBefore(node, oldNode));
    } else {
      parent.insertBefore(newContent, oldNode);
    }
    parent.removeChild(oldNode);
  }
}

记住这张表 + 2 句口诀,
你就已经达到“XML DOM 替换节点”的宗师级别,任何替换需求都能 5 秒写完!

需要我给你一个“一键替换 + 预览变化 + 撤销功能”的 XML 编辑器小工具,随时说一声~

文章已创建 2732

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部