From 1afd214b4c6ed965b75ece5e8d75febad8bc7c07 Mon Sep 17 00:00:00 2001 From: MDN Date: Thu, 27 May 2021 00:56:56 +0000 Subject: [CRON] sync translated content --- .../web/api/childnode/replacewith/index.html | 112 +++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 files/zh-cn/orphaned/web/api/childnode/replacewith/index.html (limited to 'files/zh-cn/orphaned') diff --git a/files/zh-cn/orphaned/web/api/childnode/replacewith/index.html b/files/zh-cn/orphaned/web/api/childnode/replacewith/index.html new file mode 100644 index 0000000000..9f3ef5bd88 --- /dev/null +++ b/files/zh-cn/orphaned/web/api/childnode/replacewith/index.html @@ -0,0 +1,112 @@ +--- +title: ChildNode.replaceWith() +slug: orphaned/Web/API/ChildNode/replaceWith +tags: + - DOM + - Node +translation_of: Web/API/ChildNode/replaceWith +original_slug: Web/API/ChildNode/replaceWith +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

ChildNode.replaceWith() 的方法用一套 {{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象,替换了该节点父节点下的子节点 。{{domxref("DOMString")}} 对象被当做等效的{{domxref("Text")}} 节点插入。

+ +

语法

+ +
[Throws, Unscopable]
+void ChildNode.replaceWith((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
节点
+
一系列用来替换的{{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象。
+
+ +

例外

+ + + +

案例

+ +

Using replaceWith()

+ +
var parent = document.createElement("div");
+var child = document.createElement("p");
+parent.appendChild(child);
+var span = document.createElement("span");
+
+child.replaceWith(span);
+
+console.log(parent.outerHTML);
+// "<div><span></span></div>"
+
+ +

ChildNode.replaceWith() is unscopable

+ +

replaceWith()的方法并没有作用于with语句. 参考 {{jsxref("Symbol.unscopables")}} 获取更多信息.

+ +
with(node) {
+  replaceWith("foo");
+}
+// ReferenceError: replaceWith is not defined 
+ +

Polyfill

+ +

你可以在IE9及更高级的浏览器中使用下面的代码向上兼容replaceWith()的方法:

+ +
(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('replaceWith')) {
+      return;
+    }
+    Object.defineProperty(item, 'replaceWith', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function replaceWith() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.parentNode.replaceChild(docFrag, this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

规范

+ + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG', '#dom-childnode-replacewith', 'ChildNode.replacewith()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{Compat("api.ChildNode.replaceWith")}}

+ +

参阅

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