From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/web/api/node/replacechild/index.html | 99 ++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 files/zh-cn/web/api/node/replacechild/index.html (limited to 'files/zh-cn/web/api/node/replacechild') diff --git a/files/zh-cn/web/api/node/replacechild/index.html b/files/zh-cn/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..e346fcb0c2 --- /dev/null +++ b/files/zh-cn/web/api/node/replacechild/index.html @@ -0,0 +1,99 @@ +--- +title: Node.replaceChild() +slug: Web/API/Node/replaceChild +tags: + - API + - DOM + - Node + - 参考 + - 方法 +translation_of: Web/API/Node/replaceChild +--- +
{{APIRef("DOM")}}
+ +

Node.replaceChild() 方法用指定的节点替换当前节点的一个子节点,并返回被替换掉的节点。

+ +

语法

+ +
parentNode.replaceChild(newChild, oldChild);
+
+ +

参数

+ +
+
newChild
+
用来替换 oldChild 的新节点。如果该节点已经存在于 DOM 树中,则它首先会被从原始位置删除。
+
oldChild
+
被替换掉的原始节点。
+
+ + + +

返回值

+ +

The returned value is the replaced node. This is the same node as oldChild.

+ +

例子

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// 创建一个空的span元素节点
+// 没有id,没有任何属性和内容
+var sp1 = document.createElement("span");
+
+// 添加一个id属性,值为'newSpan'
+sp1.setAttribute("id", "newSpan");
+
+// 创建一个文本节点
+var sp1_content = document.createTextNode("新的span元素的内容.");
+
+// 将文本节点插入到span元素中
+sp1.appendChild(sp1_content);
+
+// 获得被替换节点和其父节点的引用.
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// 用新的span元素sp1来替换掉sp2
+parentDiv.replaceChild(sp1, sp2);
+
+// 结果:
+// <div>
+//   <span id="newSpan">新的span元素的内容.</span>
+// </div>
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("DOM WHATWG", "#dom-node-replacechild", "Node: replaceChild")}}{{Spec2("DOM WHATWG")}}
+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.replaceChild")}}

+ +

参见

+ + -- cgit v1.2.3-54-g00ecf