replacechild 是 dom 节点方法,需通过父节点调用:parentnode.replacechild(newchild, oldchild),其中 newchild 和 oldchild 均为 node 类型且 oldchild 必须是 parentnode 的直接子节点。

replaceChild 是 DOM 节点的方法,不是 JavaScript 字符串方法,也不能直接用于“替换页面中的指定节点”而不先获取目标节点和新节点。它必须在父节点上调用,把它的某个子节点替换成另一个节点。
基本用法:必须通过父节点调用
语法是:parentNode.replaceChild(newChild, oldChild)。注意两点:
- newChild 是你要插入的新节点(必须是 Node 类型,比如元素、文本节点等)
- oldChild 是父节点下**已存在的子节点**,必须精确匹配(不能是选择器字符串或 ID 字符串)
完整操作步骤(以替换一个 div 为例)
假设 HTML 中有:<div id="container"><p id="old">旧内容</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill9063" title="chartjs-reporter"><img
src="https://img.php.cn/upload/skill/000/000/081/179239514984446.jpg" alt="chartjs-reporter" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill9063" title="chartjs-reporter" class="overflowclass">chartjs-reporter</a>
<p class="overflowclass">此技能用于在用户需要将结构化数据(查询结果、CSV 摘要、JSON 记录或 Python 字典/列表)转换为独立的 HTML 页面时使用。</p>
</div>
<a rel="nofollow" href="/xiazai/skill9063" title="chartjs-reporter" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div></div>
- 先获取父节点:
const container = document.getElementById('container'); - 再获取要被替换的旧节点:
const oldP = document.getElementById('old'); - 创建或获取新节点(例如新建一个 ):
const newSpan = document.createElement('span'); newSpan.textContent = '新内容'; - 最后调用 replaceChild:
container.replaceChild(newSpan, oldP);
常见错误和注意事项
容易出错的地方:
- 如果
oldChild不是parentNode的直接子节点,会报错 “The node to be replaced is not a child of this node” - 如果
newChild已经存在于文档中,它会先从原位置移除,再插入到新位置(DOM 节点不能重复存在) - 不能用字符串(如
'<div>xxx</div>')直接当 newChild —— 必须是 Node 对象,可用innerHTML+firstElementChild或DOMParser解析
快捷替代方案(更常用)
实际开发中,直接用 replaceChild 较少,更多用语义更清晰的方式:
-
oldChild.replaceWith(newChild)—— 现代浏览器支持(IE 不支持),直接在旧节点上调用,无需找父节点 -
parentNode.insertBefore(newChild, oldChild); parentNode.removeChild(oldChild);—— 兼容性最好,效果等价 - 用
innerHTML替换整个内容(适合纯 HTML 字符串,但会销毁事件监听器和已有状态)










