From b9afb23d12dcae1e09f8d04c72143c5ddaa34aea Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Fri, 16 Jul 2021 16:27:00 -0400 Subject: delete conflicting/orphaned docs (zh-CN) (#1412) * delete conflicting docs (zh-CN) * and redirects * do orphaned as well * fix * remove more orphans * revert orphaned docs that can identify origin * move orphaned docs to current loc * adjust slug path * fix redirect change from rebase Co-authored-by: Irvin --- files/zh-cn/web/api/element/after/index.html | 176 +++++++++++++++++++ files/zh-cn/web/api/element/append/index.html | 148 ++++++++++++++++ files/zh-cn/web/api/element/before/index.html | 188 +++++++++++++++++++++ .../web/api/element/childelementcount/index.html | 15 +- files/zh-cn/web/api/element/children/index.html | 123 ++++++++++++++ .../web/api/element/firstelementchild/index.html | 101 +++++++++++ .../web/api/element/lastelementchild/index.html | 99 +++++++++++ files/zh-cn/web/api/element/prepend/index.html | 134 +++++++++++++++ files/zh-cn/web/api/element/remove/index.html | 96 +++++++++++ .../web/api/element/replacechildren/index.html | 170 +++++++++++++++++++ files/zh-cn/web/api/element/replacewith/index.html | 112 ++++++++++++ 11 files changed, 1357 insertions(+), 5 deletions(-) create mode 100644 files/zh-cn/web/api/element/after/index.html create mode 100644 files/zh-cn/web/api/element/append/index.html create mode 100644 files/zh-cn/web/api/element/before/index.html create mode 100644 files/zh-cn/web/api/element/children/index.html create mode 100644 files/zh-cn/web/api/element/firstelementchild/index.html create mode 100644 files/zh-cn/web/api/element/lastelementchild/index.html create mode 100644 files/zh-cn/web/api/element/prepend/index.html create mode 100644 files/zh-cn/web/api/element/remove/index.html create mode 100644 files/zh-cn/web/api/element/replacechildren/index.html create mode 100644 files/zh-cn/web/api/element/replacewith/index.html (limited to 'files/zh-cn/web/api/element') diff --git a/files/zh-cn/web/api/element/after/index.html b/files/zh-cn/web/api/element/after/index.html new file mode 100644 index 0000000000..76792e7638 --- /dev/null +++ b/files/zh-cn/web/api/element/after/index.html @@ -0,0 +1,176 @@ +--- +title: ChildNode.after() +slug: orphaned/Web/API/ChildNode/after +translation_of: Web/API/ChildNode/after +original_slug: Web/API/ChildNode/after +--- +
{{APIRef("DOM")}}
+ +

ChildNode.after() 方法会在其父节点的子节点列表中插入一些 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。插入位置为该节点之后。{{domxref("DOMString")}} 对象会被以 {{domxref("Text")}} 的形式插入。

+ +

语法

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

参数

+ +
+
nodes
+
一组准备插入的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 。
+
+ +

错误

+ + + +

示例

+ +

插入元素

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

插入文本

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

同时插入元素和文本

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

ChildNode.after() 会被 with 环境排除

+ +

after() 方法不在 with 环境的范围内,可以查看 {{jsxref("Symbol.unscopables")}} 来了解更多信息。

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

Polyfill

+ +

You can polyfill the after() method in Internet Explorer 9 and higher with the following code:

+ +
// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('after')) {
+      return;
+    }
+    Object.defineProperty(item, 'after', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function after() {
+        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.insertBefore(docFrag, this.nextSibling);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Another polyfill

+ +
// from: https://github.com/FabioVergani/js-Polyfill_Element.prototype.after/blob/master/after.js
+
+(function(x){
+ var o=x.prototype,p='after';
+ if(!o[p]){
+    o[p]=function(){
+     var e, m=arguments, l=m.length, i=0, t=this, p=t.parentNode, n=Node, s=String, d=document;
+     if(p!==null){
+        while(i<l){
+         e=m[i];
+         if(e instanceof n){
+            t=t.nextSibling;
+            if(t!==null){
+                p.insertBefore(e,t);
+            }else{
+                p.appendChild(e);
+            };
+         }else{
+            p.appendChild(d.createTextNode(s(e)));
+         };
+         ++i;
+        };
+     };
+    };
+ };
+})(Element);
+
+
+
+/*
+minified:
+
+(function(x){
+ var o=x.prototype;
+ o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentNode,n=Node,s=String,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextSibling )!==null)?p.insertBefore(e,t):p.appendChild(e)):p.appendChild(d.createTextNode(s(e)));++i;}}});
+}(Element));
+*/
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-childnode-after', 'ChildNode.after()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/append/index.html b/files/zh-cn/web/api/element/append/index.html new file mode 100644 index 0000000000..00d22e2232 --- /dev/null +++ b/files/zh-cn/web/api/element/append/index.html @@ -0,0 +1,148 @@ +--- +title: Element.append() +slug: Web/API/Element/append +translation_of: Web/API/Element/append +tags: + - API + - DOM + - Method + - Node + - Element + - Reference +browser-compat: api.Element.append +--- +
{{APIRef("DOM")}}
+ +
 Element.append 方法在 Element的最后一个子节点之后插入一组 {{domxref("Node")}} 对象或 {{domxref("DOMString")}} 对象。
+ +
被插入的 {{domxref("DOMString")}} 对象等价为 {{domxref("Text")}} 节点。
+ +
+ +
与 {{domxref("Node.appendChild()")}} 的差异:
+ +
+ + + +

语法

+ +
[Throws, Unscopable]
+void Element.append((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
nodes
+
一组要插入的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。
+
+ +

异常

+ + + +

示例

+ +

插入一个元素节点

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.append(p);
+
+console.log(parent.childNodes); // NodeList [ <p> ]
+
+ +

插入文本

+ +
var parent = document.createElement("div");
+parent.append("Some text");
+
+console.log(parent.textContent); // "Some text"
+ +

插入一个节点,同时插入一些文本

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.append("Some text", p);
+
+console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
+ +

Element.append() 方法在 with 语句中不生效

+ +

为了保证向后兼容,append 方法在 with 语句中会被特殊处理,详情请看 {{jsxref("Symbol.unscopables")}}。

+ +
var parent = document.createElement("div");
+
+with(parent) {
+  append("foo");
+}
+// ReferenceError: append is not defined 
+ +

Polyfill

+ +

下面的 Polyfill 只支持到 IE 9  及以上:

+ +
// Source: https://github.com/jserz/js_piece/blob/master/DOM/Element/append()/append().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('append')) {
+      return;
+    }
+    Object.defineProperty(item, 'append', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function append() {
+        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.appendChild(docFrag);
+      }
+    });
+  });
+})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-Element-append', 'Element.append()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容

+ + + +

{{Compat("api.Element.append")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/before/index.html b/files/zh-cn/web/api/element/before/index.html new file mode 100644 index 0000000000..add3dab015 --- /dev/null +++ b/files/zh-cn/web/api/element/before/index.html @@ -0,0 +1,188 @@ +--- +title: ChildNode.before() +slug: orphaned/Web/API/ChildNode/before +tags: + - api、dom、节点、方法 +translation_of: Web/API/ChildNode/before +original_slug: Web/API/ChildNode/before +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

 ChildNode.before 方法可以在ChildNode这个节点的父节点中插入一些列的 {{domxref("Node")}} 或者 {{domxref("DOMString")}} 对象,位置就是在ChildNode节点的前面,{{domxref("DOMString")}} 对象其实和 {{domxref("Text")}}节点一样的方式来完成插入的。

+ +

语法

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

Parameters参数

+ +
+
nodes
+
一系列的 {{domxref("Node")}} 或者 {{domxref("DOMString")}} 
+
+ +

Exceptions

+ + + +

Examples事例

+ +

Inserting an element插入元素节点

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

Inserting text插入文本节点

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

Inserting an element and text同时插入文本和元素

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

ChildNode.before() is unscopable不可使用区域

+ +

The before() 不能配合with声明使用,See {{jsxref("Symbol.unscopables")}} for more information.

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

Polyfill

+ +

兼容ie9或者更高版本的方法,You can polyfill the before() method in Internet Explorer 9 and higher with the following code:

+ +
// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/before()/before().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('before')) {
+      return;
+    }
+    Object.defineProperty(item, 'before', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function before() {
+        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.insertBefore(docFrag, this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Specification

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-childnode-before', 'ChildNode.before()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(54.0)}}{{CompatGeckoDesktop(49)}}{{CompatUnknown}}{{CompatOpera(39)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(54.0)}}{{CompatGeckoMobile(49)}}{{CompatUnknown}}{{CompatOpera(39)}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/childelementcount/index.html b/files/zh-cn/web/api/element/childelementcount/index.html index 11a680d8a0..8981c4ad50 100644 --- a/files/zh-cn/web/api/element/childelementcount/index.html +++ b/files/zh-cn/web/api/element/childelementcount/index.html @@ -1,15 +1,20 @@ --- -title: ParentNode.childElementCount +title: Element.childElementCount slug: Web/API/Element/childElementCount -translation_of: Web/API/ParentNode/childElementCount -original_slug: Web/API/ParentNode/childElementCount +translation_of: Web/API/Element/childElementCount +tags: + - API + - DOM + - Property + - Reference +browser-compat: api.Element.childElementCount ---

{{ APIRef("DOM") }} 

-

 ParentNode.childElementCount 只读属性返回一个无符号长整型数字,表示给定元素的子元素数。

+

 Element.childElementCount 只读属性返回一个无符号长整型数字,表示给定元素的子元素数。

-

This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("ParentNode")}} and {{domxref("ChildNode")}}. In this case, childElementCount moved to {{domxref("ParentNode")}}. This is a fairly technical change that shouldn't affect compatibility.

+

This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("Element")}} and {{domxref("ChildNode")}}. In this case, childElementCount moved to {{domxref("Element")}}. This is a fairly technical change that shouldn't affect compatibility.

 

diff --git a/files/zh-cn/web/api/element/children/index.html b/files/zh-cn/web/api/element/children/index.html new file mode 100644 index 0000000000..9690827104 --- /dev/null +++ b/files/zh-cn/web/api/element/children/index.html @@ -0,0 +1,123 @@ +--- +title: Element.children +slug: Web/API/Element/children +translation_of: Web/API/Element/children +tags: + - API + - DOM + - Element + - HTMLCollection + - Property + - children +browser-compat: api.Element.children +--- +

{{ APIRef("DOM") }}

+ +

Element.children 是一个只读属性,返回 一个Node的子{{domxref("Element","elements")}} ,是一个动态更新的 {{domxref("HTMLCollection")}}。

+ +

语法

+ +
var children = node.children;
+ +
var elList = elementNodeReference.children;
+
+ +

备注

+ +

children 属性为只读属性,对象类型为 {{ domxref("HTMLCollection") }},你可以使用 elementNodeReference.children[1].nodeName 来获取某个子元素的标签名称。

+ +

例子

+ +
// parg是一个指向<p>元素的对象引用
+if (parg.childElementCount)
+// 检查这个<p>元素是否有子元素
+// 译者注:childElementCount有兼容性问题
+ {
+   var children = parg.children;
+   for (var i = 0; i < children.length; i++)
+   {
+   // 通过children[i]来获取每个子元素
+   // 注意:List是一个live的HTMLCollection对象,在这里添加或删除parg的子元素节点,都会立即改变List的值.
+   };
+ };
+
+ +

规范

+ +

 

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-Element-children', 'Element.children')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support13.59 (IE6-8 incl commend nodes)104
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

[1] Internet Explorer 6 - 8 支持该属性,但是可能会错误地包含注释 {{domxref("Comment")}} 节点。

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/firstelementchild/index.html b/files/zh-cn/web/api/element/firstelementchild/index.html new file mode 100644 index 0000000000..dbbc7868e1 --- /dev/null +++ b/files/zh-cn/web/api/element/firstelementchild/index.html @@ -0,0 +1,101 @@ +--- +title: Element.firstElementChild +slug: Web/API/Element/firstElementChild +translation_of: Web/API/Element/firstElementChild +tags: + - API + - DOM + - Element + - Property +browser-compat: api.Element.firstElementChild +--- +

{{ APIRef("DOM") }}

+ +

Element.firstElementChild 只读属性,返回对象的第一个子 {{domxref("元素")}}, 如果没有子元素,则为null。

+ +
+

他的属性最初是在{{domxref("element遍历")}}纯接口中定义的。由于这个接口包含两组不同的属性,一个针对具有子元素的{{domxref("Node")}},一个针对子元素的属性,因此它们被移动到两个单独的纯接口中,{{domxref("Element")}}和{{domxref("ChildNode")}}。在本例中,firstElementChild移动到{{domxref("Element")}}。这是一个相当技术性的更改,不应该影响兼容性。

+
+ +

语法

+ +
var element = node.firstElementChild;
+
+ +

例子

+ +
<ul id="foo">
+  <li>First  (1)</li>
+  <li>Second (2)</li>
+  <li>Third  (3)</li>
+</ul>
+
+<script>
+var foo = document.getElementById('foo');
+// yields: First  (1)
+console.log(foo.firstElementChild.textContent);
+</script>
+
+ +

适用于 IE8、IE9 和 Safari 的 Polyfill

+ +
// Overwrites native 'firstElementChild' prototype.
+// Adds Document & DocumentFragment support for IE9 & Safari.
+// Returns array instead of HTMLCollection.
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.firstElementChild == null) {
+        Object.defineProperty(constructor.prototype, 'firstElementChild', {
+            get: function() {
+                var node, nodes = this.childNodes, i = 0;
+                while (node = nodes[i++]) {
+                    if (node.nodeType === 1) {
+                        return node;
+                    }
+                }
+                return null;
+            }
+        });
+    }
+})(window.Node || window.Element);
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-Element-firstelementchild', 'Element.firstElementChild')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversalinterface in {{domxref("ChildNode")}} and Element. This method is now defined on the latter.
+ The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.
{{SpecName('Element Traversal', '#attribute-firstElementChild', 'ElementTraversal.firstElementChild')}}{{Spec2('Element Traversal')}}Added its initial definition to theElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Element.firstElementChild")}}

+ +

参见

+ +

Ed

+ + diff --git a/files/zh-cn/web/api/element/lastelementchild/index.html b/files/zh-cn/web/api/element/lastelementchild/index.html new file mode 100644 index 0000000000..21a33fd6b6 --- /dev/null +++ b/files/zh-cn/web/api/element/lastelementchild/index.html @@ -0,0 +1,99 @@ +--- +title: Element.lastElementChild +slug: Web/API/Element/lastElementChild +translation_of: Web/API/Element/lastElementChild +tags: + - API + - DOM + - Element + - Property +browser-compat: api.Element.lastElementChild +--- +

{{ APIRef("DOM") }}

+ +

只读属性 Element.lastElementChild 返回对象的最后一个子{{domxref("Element", "元素")}},如果没有子元素,则返回 null

+ +
+

This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("Element")}} and {{domxref("ChildNode")}}. In this case, lastElementChild moved to {{domxref("Element")}}. This is a fairly technical change that shouldn't affect compatibility.

+
+ +

语法

+ +
var element = node.lastElementChild; 
+ +

例子

+ +
<ul id="foo">
+  <li>First  (1)</li>
+  <li>Second (2)</li>
+  <li>Third  (3)</li>
+</ul>
+
+<script>
+var foo = document.getElementById('foo');
+// yields: Third  (3)
+console.log(foo.lastElementChild.textContent);
+</script>
+
+ +

适用于 IE8、IE9 和 Safari 的 Polyfill

+ +
// Overwrites native 'lastElementChild' prototype.
+// Adds Document & DocumentFragment support for IE9 & Safari.
+// Returns array instead of HTMLCollection.
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.lastElementChild == null) {
+        Object.defineProperty(constructor.prototype, 'lastElementChild', {
+            get: function() {
+                var node, nodes = this.childNodes, i = nodes.length - 1;
+                while (node = nodes[i--]) {
+                    if (node.nodeType === 1) {
+                        return node;
+                    }
+                }
+                return null;
+            }
+        });
+    }
+})(window.Node || window.Element);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-Element-lastelementchild', 'Element.lastElementChild')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversal interface in {{domxref("ChildNode")}} and Element. This method is now defined on the latter.
+ The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.
{{SpecName('Element Traversal', '#attribute-lastElementChild', 'ElementTraversal.lastElementChild')}}{{Spec2('Element Traversal')}}Added its initial definition to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Element.lastElementChild")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/prepend/index.html b/files/zh-cn/web/api/element/prepend/index.html new file mode 100644 index 0000000000..eb7edc31cd --- /dev/null +++ b/files/zh-cn/web/api/element/prepend/index.html @@ -0,0 +1,134 @@ +--- +title: Element.prepend() +slug: Web/API/Element/prepend +translation_of: Web/API/Element/prepend +tags: + - API + - DOM + - Method + - Node + - Element + - Reference + - prepend +browser-compat: api.Element.prepend +--- +
{{APIRef("DOM")}}
+ +

Element.prepend 方法可以在父节点的第一个子节点之前插入一系列{{domxref("Node")}}对象或者{{domxref("DOMString")}}对象。{{domxref("DOMString")}}会被当作{{domxref("Text")}}节点对待(也就是说插入的不是HTML代码)。

+ +

语法

+ +
Element.prepend((Node or DOMString)... nodes);
+
+ +

参数

+ +
+
nodes
+
要插入的一系列{{domxref("Node")}}或者{{domxref("DOMString")}}。
+
+ +

返回值

+ +

undefined.

+ +

错误

+ + + +

例子

+ +

Prepending an element

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+var span = document.createElement("span");
+parent.append(p);
+parent.prepend(span);
+
+console.log(parent.childNodes); // NodeList [ <span>, <p> ]
+
+ +

Prepending text

+ +
var parent = document.createElement("div");
+parent.append("Some text");
+parent.prepend("Headline: ");
+
+console.log(parent.textContent); // "Headline: Some text"
+ +

Appending an element and text

+ +
var parent = document.createElement("div");
+var p = document.createElement("p");
+parent.prepend("Some text", p);
+
+console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
+ +

Element.prepend() is unscopable

+ +

prepend()不能在with语句内使用,详情参考{{jsxref("Symbol.unscopables")}}。

+ +
var parent = document.createElement("div");
+
+with(parent) {
+  prepend("foo");
+}
+// ReferenceError: prepend is not defined 
+ +

Polyfill

+ +

使用下面的代码在IE9或更高版本中模拟prepend()方法:

+ +
// from: https://github.com/jserz/js_piece/blob/master/DOM/Element/prepend()/prepend().md
+(function (arr) {
+    arr.forEach(function (item) {
+        item.prepend = item.prepend || function () {
+            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.insertBefore(docFrag, this.firstChild);
+        };
+    });
+})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
+ +

说明

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-Element-prepend', 'Element.prepend()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

兼容性

+ + + +

{{Compat("api.Element.prepend")}}

+ +

See also

+ + diff --git a/files/zh-cn/web/api/element/remove/index.html b/files/zh-cn/web/api/element/remove/index.html new file mode 100644 index 0000000000..b60cab7a0c --- /dev/null +++ b/files/zh-cn/web/api/element/remove/index.html @@ -0,0 +1,96 @@ +--- +title: ChildNode.remove() +slug: orphaned/Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Method +translation_of: Web/API/ChildNode/remove +original_slug: Web/API/ChildNode/remove +--- +

{{APIRef("DOM")}}

+ +

ChildNode.remove() 方法,把对象从它所属的 DOM 树中删除。

+ +

语法

+ +
node.remove();
+ +

示例

+ +

使用 remove()

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+<div id="div-03">Here is div-03</div>
+
+ +
var el = document.getElementById('div-02');
+el.remove();
+// id 为 'div-02' 的 div 被删掉了
+
+ +

{{EmbedLiveSample('使用_remove()')}}

+ +

ChildNode.remove() 是不可见的

+ +

with 语句中,remove() 方法是不可见的。参阅 {{jsxref("Symbol.unscopables")}} 了解更多信息。

+ +
with(node) {
+  remove();
+}
+// ReferenceError: remove is not defined
+ +

Polyfill

+ +

You can polyfill the remove() method in Internet Explorer 9 and higher with the following code:

+ +
//https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
+(function (arr) {
+   arr.forEach(function (item) {
+    if (item.hasOwnProperty('remove')) {
+      return;
+    }
+    Object.defineProperty(item, 'remove', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function remove() {
+        this.parentNode.removeChild(this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

规范

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

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/api/element/replacechildren/index.html b/files/zh-cn/web/api/element/replacechildren/index.html new file mode 100644 index 0000000000..c15e75961e --- /dev/null +++ b/files/zh-cn/web/api/element/replacechildren/index.html @@ -0,0 +1,170 @@ +--- +title: Element.replaceChildren() +slug: Web/API/Element/replaceChildren +translation_of: Web/API/Element/replaceChildren +tags: + - API + - DOM + - Method + - Node + - Element + - Reference + - replaceChildren +browser-compat: api.Element.replaceChildren +--- +
{{APIRef("DOM")}}{{seecompattable}}
+ +

Element.replaceChildren() 方法将一个 {{domxref("Node")}} 的后代替换为指定的后代集合。这些新的后代可以为 {{domxref("DOMString")}} 或 {{domxref("Node")}} 对象。

+ +

语法

+ +
// [Throws, Unscopable]
+Element.replaceChildren(...nodesOrDOMStrings) // 返回 undefined
+
+ +

参数

+ +
+
nodesOrDOMStrings
+
一组用于替换 Element 现有后代的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。若没有指定替代对象时,Element 的所有后代都将被清空。
+
+ +

异常

+ + + +

例子

+ +

清空一个节点

+ +

replaceChildren() 为清空一个节点的后代提供了非常方便的机制,您只需在父节点不指定任何实参调用该方法即可。

+ +
myNode.replaceChildren();
+ +

在父节点之间转移节点

+ +

replaceChildren() 允许您更轻松地在父节点之间转移节点,而无需依赖冗余的循环代码。例如,有一个简单的应用程序让您选择您派对上的食物。它的 HTML 可能如下:

+ +
<h2>派对食物列表</h2>
+
+<main>
+  <div>
+    <label for="no">不,谢谢了!</label>
+
+    <select id="no" multiple size="10">
+      <option>苹果</option>
+      <option>橘子</option>
+      <option>葡萄</option>
+      <option>香蕉</option>
+      <option>奇异果</option>
+      <option>巧克力饼干</option>
+      <option>花生饼干</option>
+      <option>巧克力棒</option>
+      <option>火腿三明治</option>
+      <option>乳酪三明治</option>
+      <option>沙拉三明治</option>
+      <option>冰淇淋</option>
+      <option>果冻</option>
+      <option>胡萝卜和鹰嘴豆泥</option>
+      <option>玛格丽特披萨</option>
+      <option>腊肠比萨</option>
+      <option>素比萨</option>
+    </select>
+  </div>
+
+  <div class="buttons">
+    <button id="to-yes">转移到"是" --&gt;</button>
+    <button id="to-no">&lt;-- 转移到 "否"</button>
+  </div>
+
+  <div>
+    <label for="yes">是的,请!</label>
+
+    <select id="yes" multiple size="10">
+
+    </select>
+  </div>
+</main>
+ +

使用一些简单的 CSS 将两个选择列表排成一行,并将控制按钮放置在它们之间是很有意义的:

+ +
main {
+  display: flex;
+}
+
+div {
+  margin-right: 20px;
+}
+
+label, button {
+  display: block;
+}
+
+.buttons {
+  display: flex;
+  flex-flow: column;
+  justify-content: center;
+}
+
+select {
+  width: 200px;
+}
+ +

我们要做的是,当按下 “是” 按钮时,将 “否” 列表中的所有选定选项都转移到 “是” 列表中,然后当按下“否”按钮时,将 “是” 列表中的所有选定选项都转移到 “否” 列表中。

+ +

为此,我们为每个按钮提供一个 click 事件处理句柄,该事件句柄将所选选项赋值到第一个常量中,将要转移到的列表中的现有的选项赋值到第二个常量中。然后,它会调用列表的 replaceChildren() 方法,使用延展运算符传入两个常量,进而将两个常量中包含的所有选项转移到目标列表。

+ +
const noSelect = document.getElementById('no');
+const yesSelect = document.getElementById('yes');
+const noBtn = document.getElementById('to-no');
+const yesBtn = document.getElementById('to-yes');
+
+yesBtn.addEventListener('click', () => {
+  const selectedTransferOptions = document.querySelectorAll('#no option:checked');
+  const existingYesOptions = document.querySelectorAll('#yes option');
+  yesSelect.replaceChildren(...selectedTransferOptions, ...existingYesOptions);
+});
+
+noBtn.addEventListener('click', () => {
+  const selectedTransferOptions = document.querySelectorAll('#yes option:checked');
+  const existingNoOptions = document.querySelectorAll('#no option');
+  noSelect.replaceChildren(...selectedTransferOptions, ...existingNoOptions);
+});
+ +

最终结果如下:

+ +

{{EmbedLiveSample('Transferring_nodes_between_parents', '100%', '350')}}

+ +

规范

+ + + + + + + + + + + + + + +
规范状态备注
{{SpecName('DOM WHATWG', '#dom-Element-replacechildren', 'Element.replaceChildren()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.Element.replaceChildren")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/element/replacewith/index.html b/files/zh-cn/web/api/element/replacewith/index.html new file mode 100644 index 0000000000..9f3ef5bd88 --- /dev/null +++ b/files/zh-cn/web/api/element/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