From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- files/zh-tw/web/api/node/childnodes/index.html | 66 +++ files/zh-tw/web/api/node/clonenode/index.html | 160 +++++++ files/zh-tw/web/api/node/index.html | 529 ++++++++++++++++++++++ files/zh-tw/web/api/node/innertext/index.html | 86 ++++ files/zh-tw/web/api/node/insertbefore/index.html | 167 +++++++ files/zh-tw/web/api/node/nodename/index.html | 102 +++++ files/zh-tw/web/api/node/nodetype/index.html | 171 +++++++ files/zh-tw/web/api/node/ownerdocument/index.html | 111 +++++ files/zh-tw/web/api/node/removechild/index.html | 133 ++++++ files/zh-tw/web/api/node/textcontent/index.html | 158 +++++++ 10 files changed, 1683 insertions(+) create mode 100644 files/zh-tw/web/api/node/childnodes/index.html create mode 100644 files/zh-tw/web/api/node/clonenode/index.html create mode 100644 files/zh-tw/web/api/node/index.html create mode 100644 files/zh-tw/web/api/node/innertext/index.html create mode 100644 files/zh-tw/web/api/node/insertbefore/index.html create mode 100644 files/zh-tw/web/api/node/nodename/index.html create mode 100644 files/zh-tw/web/api/node/nodetype/index.html create mode 100644 files/zh-tw/web/api/node/ownerdocument/index.html create mode 100644 files/zh-tw/web/api/node/removechild/index.html create mode 100644 files/zh-tw/web/api/node/textcontent/index.html (limited to 'files/zh-tw/web/api/node') diff --git a/files/zh-tw/web/api/node/childnodes/index.html b/files/zh-tw/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..a828bd781b --- /dev/null +++ b/files/zh-tw/web/api/node/childnodes/index.html @@ -0,0 +1,66 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +translation_of: Web/API/Node/childNodes +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.childNodes 唯讀屬性會回傳一個即時更新的動態集合(live collection),其包含了指定元素的子{{domxref("Node","節點")}},而第一個子節點會被指派為索引 0。

+ +

語法

+ +
var ndList = elementNodeReference.childNodes;
+
+ +

ndList 是一個 {{domxref("NodeList")}},為一個有順序性、由目前元素之 DOM 子節點組成之集合。假如目前元素沒有子節點,則 ndList 會是空的。

+ +

範例

+ +
// parg is an object reference to a <p> element
+
+// First check that the element has child nodes
+if (parg.hasChildNodes()) {
+  var children = parg.childNodes;
+
+  for (var i = 0; i < children.length; i++) {
+    // do something with each child as children[i]
+    // NOTE: List is live, adding or removing children will change the list
+  }
+}
+ +
+
// This is one way to remove all children from a node
+// box is an object reference to an element
+
+while (box.firstChild) {
+    //The list is LIVE so it will re-index each call
+    box.removeChild(box.firstChild);
+}
+ +

備註

+ +

The items in the collection of nodes are objects and not strings. To get data from node objects, use their properties (e.g. elementNodeReference.childNodes[1].nodeName to get the name, etc.).

+ +

The document object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement. (In (X)HTML documents this is the HTML element.)

+ +

childNodes includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use {{ domxref("ParentNode.children") }} instead.

+ +

規範

+ + + +

參見

+ + diff --git a/files/zh-tw/web/api/node/clonenode/index.html b/files/zh-tw/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..2bd1998650 --- /dev/null +++ b/files/zh-tw/web/api/node/clonenode/index.html @@ -0,0 +1,160 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +

Node.cloneNode() 方法會回傳一個呼叫此方法之節點物件的拷貝。

+ +

語法

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
The node to be cloned.
+
dupNode
+
The new node that will be a clone of node
+
deep {{optional_inline}}
+
true if the children of the node should also be cloned, or false to clone only the specified node.
+
+ +
+

Note: In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), deep is an optional argument. If omitted, the method acts as if the value of deep was true, defaulting to using deep cloning as the default behavior. To create a shallow clone, deep must be set to false.

+ +

This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of deep was false. Though It's still optional, you should always provide the deep argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}), the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.

+
+ +

範例

+ +
var p = document.getElementById("para1");
+var p_prime = p.cloneNode(true);
+
+ +

備註

+ +

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties. (e.g. node.onclick = fn) Moreover, for a <canvas> element, the painted image is not copied.

+ +

The duplicate node returned by cloneNode() is not part of the document until it is added to another node that is part of the document using {{domxref("Node.appendChild()")}} or a similar method. It also has no parent until it is appended to another node.

+ +

If deep is set to false, child nodes are not cloned. Any text that the node contains is not cloned either, as it is contained in one or more child {{domxref("Text")}} nodes.

+ +

If deep evaluates to true, the whole subtree (including text that may be in child {{domxref("Text")}} nodes) is copied too. For empty nodes (e.g. {{HTMLElement("img")}} and {{HTMLElement("input")}} elements) it doesn't matter whether deep is set to true or false.

+ +
Warning: cloneNode() may lead to duplicate element IDs in a document.
+ +

If the original node has an ID and the clone is to be placed in the same document, the ID of the clone should be modified to be unique. Name attributes may need to be modified also, depending on whether duplicate names are expected.

+ +

To clone a node for appending to a different document, use {{domxref("Document.importNode()")}} instead.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-node-clonenode", "Node.cloneNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM3 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM3 Core")}} 
{{SpecName("DOM2 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
deep as an optional parameter +

{{CompatVersionUnknown}}[1]

+
{{CompatUnknown}}{{CompatGeckoDesktop("13.0")}}{{CompatVersionUnknown}}{{CompatUnknown}} +

{{CompatVersionUnknown}}[1]

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
deep as an optional parameter{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Default value for the deep parameter is false.

diff --git a/files/zh-tw/web/api/node/index.html b/files/zh-tw/web/api/node/index.html new file mode 100644 index 0000000000..fc04145fce --- /dev/null +++ b/files/zh-tw/web/api/node/index.html @@ -0,0 +1,529 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - DOM Reference + - Interface + - NeedsTranslation + - Node + - Reference + - TopicStub +translation_of: Web/API/Node +--- +
{{APIRef("DOM")}}
+ +

Node 是一個被多種 DOM 類型繼承的介面,它讓各種類型的 DOM 都能以同樣的方式來操作。如繼承了相同的方法,或能以相同的方式測試。

+ +

Node 繼承自 {{domxref("EventTarget")}},而繼承了 Node 的屬性及方法的介面則有:{{domxref("Document")}}、{{domxref("Element")}}、{{domxref("CharacterData")}}(被 {{domxref("Text")}}、{{domxref("Comment")}} 以及 {{domxref("CDATASection")}} 所繼承)、{{domxref("ProcessingInstruction")}}、{{domxref("DocumentFragment")}}、{{domxref("DocumentType")}}、{{domxref("Notation")}}、{{domxref("Entity")}}、{{domxref("EntityReference")}}。

+ +

These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

Inherits properties from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the node type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
A {{ Interface("nsIPrincipal") }} representing the node principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Returns an unsigned short representing the type of the node. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
{{domxref("Node.nodeValue")}}
+
Returns / Sets the value of the current node
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
+
{{domxref("Node.parentElement")}} {{readonlyInline}}
+
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
+
{{domxref("Node.textContent")}}
+
Returns / Sets the textual content of an element and all its descendants.
+
+ +

Deprecated properties

+ +
+
{{domxref("Node.rootNode")}} {{readOnlyInline}} {{deprecated_inline}}
+
Returns a {{domxref("Node")}} object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. This has been replaced by {{domxref("Node.getRootNode()")}}.
+
+ +

Obsolete properties

+ +
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. +
+

Note: In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
The namespace URI of this node, or null if it is no namespace. +
+

Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the https://www.w3.org/1999/xhtml/ namespace in both HTML and XML trees. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
+
+ +

方法

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.appendChild()")}}
+
Adds the specified childNode argument as the last child to the current node.
+ If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position.
+
{{domxref("Node.cloneNode()")}}
+
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+
{{domxref("Node.compareDocumentPosition()")}}
+
Compares the position of the current node against another node in any other document.
+
{{domxref("Node.contains()")}}
+
Returns a {{jsxref("Boolean")}} value indicating whether a node is a descendant of a given node or not.
+
{{domxref("Node.getRootNode()")}}
+
Returns the context object's root which optionally includes the shadow root if it is available.
+
{{domxref("Node.hasChildNodes()")}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has any child nodes, or not.
+
{{domxref("Node.insertBefore()")}}
+
Inserts a {{domxref("Node")}} before the reference node as a child of the current node.
+
{{domxref("Node.isDefaultNamespace()")}}
+
Accepts a namespace URI as an argument and returns a {{jsxref("Boolean")}} with a value of true if the namespace is the default namespace on the given node or false if not.
+
{{domxref("Node.isEqualNode()")}}
+
Returns a {{jsxref("Boolean")}} which indicates whether or not two nodes are of the same type and all their defining data points match.
+
{{domxref("Node.isSameNode()")}}
+
Returns a {{jsxref("Boolean")}} value indicating whether or not the two nodes are the same (that is, they reference the same object).
+
{{domxref("Node.lookupPrefix()")}}
+
Returns a {{domxref("DOMString")}} containing the prefix for a given namespace URI, if present, and null if not. When multiple prefixes are possible, the result is implementation-dependent.
+
{{domxref("Node.lookupNamespaceURI()")}}
+
Accepts a prefix and returns the namespace URI associated with it on the given node if found (and null if not). Supplying null for the prefix will return the default namespace.
+
{{domxref("Node.normalize()")}}
+
Clean up all the text nodes under this element (merge adjacent, remove empty).
+
{{domxref("Node.removeChild()")}}
+
Removes a child node from the current element, which must be a child of the current node.
+
{{domxref("Node.replaceChild()")}}
+
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
+ +

Obsolete methods

+ +
+
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
x
+
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
+
Allows a user to get some {{domxref("DOMUserData")}} from the node.
+
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has any attributes, or not.
+
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
+
Returns a {{jsxref("Boolean")}} flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
+
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
+ +

範例

+ +

Browse all child nodes

+ +

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

+ +
function DOMComb (oParent, oCallback) {
+  if (oParent.hasChildNodes()) {
+    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
+      DOMComb(oNode, oCallback);
+    }
+  }
+  oCallback.call(oParent);
+}
+ +

Syntax

+ +
DOMComb(parentNode, callbackFunction);
+ +

Description

+ +

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

+ +

Parameters

+ +
+
parentNode
+
The parent node (Node Object).
+
callbackFunction
+
The callback function (Function).
+
+ +

Sample usage

+ +

The following example send to the console.log the text content of the body:

+ +
function printContent () {
+  if (this.nodeValue) { console.log(this.nodeValue); }
+}
+
+onload = function () {
+  DOMComb(document.body, printContent);
+};
+ +

Remove all children nested within a node

+ +
Element.prototype.removeAll = function () {
+  while (this.firstChild) { this.removeChild(this.firstChild); }
+  return this;
+};
+ +

Sample usage

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
+ Removed the following methods: isSupported(), hasAttributes(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
+ The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
+ Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
+ Added the following properties: namespaceURI, prefix, and localName.
+ Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]
getFeature(){{obsolete_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode(){{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ Removed in {{CompatGeckoDesktop("10")}}
+ Returned in {{CompatGeckoDesktop("48")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
attributes{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("22.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
rootNode(){{CompatUnknown}}{{CompatUnknown}}CompatGeckoDesktop(48)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
namespaceURI, localName, prefix {{obsolete_inline}}{{CompatVersionUnknown}}
+ {{CompatNo}}46.0[3]
{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatNo}}48.0[3]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
getRootNode(), and rootNode deprecated{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatGeckoDesktop(53)}}{{CompatUnknown}}{{CompatOpera(41)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]
getFeature(){{obsolete_inline}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
isSameNode(){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}} +

{{CompatGeckoDesktop("1.0")}}
+ Removed in {{CompatGeckoDesktop("10")}}
+ Returned in {{CompatGeckoDesktop("48")}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
rootNode(){{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
namespaceURI, localName, prefix {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatNo}}48.0[3]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
getRootNode(), and rootNode deprecated{{CompatNo}}{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatOperaMobile(41)}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
+ +

[1] WebKit and old versions of Blink incorrectly do not make Node inherit from {{domxref("EventTarget")}}.

+ +

[2] In Gecko 22.0 {{geckoRelease("22.0")}} the attributes property was moved to {{domxref("Element")}}.

+ +

[3] The properties were moved to the {{domxref("Element")}} and {{domxref("Attr")}} APIs according to the DOM4 standard.

diff --git a/files/zh-tw/web/api/node/innertext/index.html b/files/zh-tw/web/api/node/innertext/index.html new file mode 100644 index 0000000000..4c8a4272fc --- /dev/null +++ b/files/zh-tw/web/api/node/innertext/index.html @@ -0,0 +1,86 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

概述

+ +

Node.innerText 是一個代表節點及其後代之「已渲染」(rendered)文字內容的屬性。如同一個存取器,Node.innerText 近似於使用者利用游標選取成高亮後複製至剪貼簿之元素的內容。此功能最初由 Internet Explorer 提供,並在被所有主要瀏覽器採納之後,於 2016 年正式成為 HTML 標準。

+ +

{{domxref("Node.textContent")}} 屬性是一個相似的選擇,但兩者之間仍有非常不同的差異。

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for history.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{ CompatGeckoDesktop(45) }}69.6 (probably earlier)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.3 (probably earlier){{ CompatGeckoMobile(45) }}10 (probably earlier)124.1 (probably earlier)
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/node/insertbefore/index.html b/files/zh-tw/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..393cc88d80 --- /dev/null +++ b/files/zh-tw/web/api/node/insertbefore/index.html @@ -0,0 +1,167 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.insertBefore() 方法將一個節點安插在參考節點之前,作為某個特定父節點之子節點。If the given child is a reference to an existing node in the document, insertBefore() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

+ +

同一個節點並不會同時出現在兩個地方。所以當節點已經有父節點,它會先被移除,然後被插入在新的位置上。The {{domxref("Node.cloneNode()")}} can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync.

+ +

若參考節點為 null, 那需插入的節點就會成為特定父節點的最後一個子節點。

+ +

If the given child is a {{domxref("DocumentFragment")}}, the entire contents of the {{domxref("DocumentFragment")}} are moved into the child list of the specified parent node.

+ +

Syntax

+ +
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+
+ +

If referenceNode is null, the newNode is inserted at the end of the list of child nodes.

+ +
+

referenceNode 並非可選擇的參數 -- 一定要傳入一個節點或是   null。若是傳入失敗或不正確的參數,可能會依不同的瀏覽器版本而有不同的行為

+
+ +

Returns

+ +

會回傳新加入的子節點。若該值(newNode)是{{domxref("DocumentFragment")}}, 則回傳空的 {{domxref("DocumentFragment")}}。

+ +

Example

+ +
<div id="parentElement">
+   <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create the new node to insert
+var newNode = document.createElement("span");
+
+// Get a reference to the parent node
+var parentDiv = document.getElementById("childElement").parentNode;
+
+// Begin test case [ 1 ] : Exist a childElement --> All working correctly
+var sp2 = document.getElementById("childElement");
+parentDiv.insertBefore(newNode, sp2);
+// End test case [ 1 ]
+
+// Begin test case [ 2 ] : childElement is of Type undefined
+var sp2 = undefined; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
+// End test case [ 2 ]
+
+// Begin test case [ 3 ] : childElement is of Type "undefined" ( string )
+var sp2 = "undefined"; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument"
+// End test case [ 3 ]
+</script>
+ + + +

Example

+ +
<div id="parentElement">
+  <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create a new, plain <span> element
+var sp1 = document.createElement("span");
+
+// Get a reference to the element, before we want to insert the element
+var sp2 = document.getElementById("childElement");
+// Get a reference to the parent element
+var parentDiv = sp2.parentNode;
+
+// Insert the new element into the DOM before sp2
+parentDiv.insertBefore(sp1, sp2);
+</script>
+
+ +

There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling.

+ +

In the previous example, sp1 could be inserted after sp2 using:

+ +
parentDiv.insertBefore(sp1, sp2.nextSibling);
+ +

If sp2 does not have a next sibling, then it must be the last child — sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).

+ +

Example

+ +

Insert an element before the first child element, using the firstChild property.

+ +
// Get a reference to the element in which we want to insert a new node
+var parentElement = document.getElementById('parentElement');
+// Get a reference to the first child
+var theFirstChild = parentElement.firstChild;
+
+// Create a new element
+var newElement = document.createElement("div");
+
+// Insert the new element before the first child
+parentElement.insertBefore(newElement, theFirstChild);
+
+ +

When the element does not have a first child, then firstChild is null. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child either. Consequently, the new element is the only element, after insertion.

+ +

Browser compatibility

+ + + +

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

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM WHATWG')}}Fixes errors in the insertion algorithm
{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM4')}}Describes the algorithm in more detail
{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM3 Core')}}No notable changes
{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM2 Core')}}No notable changes
{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}{{Spec2('DOM1')}}Introduced
+ +

See also

+ + diff --git a/files/zh-tw/web/api/node/nodename/index.html b/files/zh-tw/web/api/node/nodename/index.html new file mode 100644 index 0000000000..b9c95b6e2f --- /dev/null +++ b/files/zh-tw/web/api/node/nodename/index.html @@ -0,0 +1,102 @@ +--- +title: Node.nodeName +slug: Web/API/Node/nodeName +translation_of: Web/API/Node/nodeName +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.nodeName 唯讀屬性會回傳目前節點名稱的字串。

+ +

不同類型節點之回傳值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
介面nodeName 值
{{domxref("Attr")}}The value of {{domxref("Attr.name")}}
{{domxref("CDATASection")}}"#cdata-section"
{{domxref("Comment")}}"#comment"
{{domxref("Document")}}"#document"
{{domxref("DocumentFragment")}}"#document-fragment"
{{domxref("DocumentType")}}The value of {{domxref("DocumentType.name")}}
{{domxref("Element")}}The value of {{domxref("Element.tagName")}}
{{domxref("Entity")}}The entity name
{{domxref("EntityReference")}}The name of entity reference
{{domxref("Notation")}}The notation name
{{domxref("ProcessingInstruction")}}The value of {{domxref("ProcessingInstruction.target")}}
{{domxref("Text")}}"#text"
+ +

語法

+ +
var str = node.nodeName;
+
+ +

範例

+ +

Given the following markup:

+ +
<div id="d1">hello world</div>
+<input type="text" id="t"/>
+
+ +

and the following script:

+ +
var div1 = document.getElementById("d1");
+var text_field = document.getElementById("t");
+
+text_field.value = div1.nodeName;
+
+ +

In XHTML (or any other XML format), text_field's value would read "div". However, in HTML, text_field's value would read "DIV", because nodeName and tagName return in upper case on HTML elements in DOMs flagged as HTML documents. Read more details on nodeName case sensitivity in different browsers.

+ +

Note that tagName property could have been used instead, since nodeName has the same value as tagName for an element. Bear in mind, however, that nodeName will return #text for text nodes while tagName will return undefined.

+ +

規範

+ + diff --git a/files/zh-tw/web/api/node/nodetype/index.html b/files/zh-tw/web/api/node/nodetype/index.html new file mode 100644 index 0000000000..606cbd1b94 --- /dev/null +++ b/files/zh-tw/web/api/node/nodetype/index.html @@ -0,0 +1,171 @@ +--- +title: Node.nodeType +slug: Web/API/Node/nodeType +translation_of: Web/API/Node/nodeType +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.nodeType 唯讀屬性表示了節點物件的類型。

+ +

描述

+ +

The nodeType property can be used to distinguish different kind of nodes, such that {{domxref("Element", "elements")}}, {{domxref("Text", "text")}} and {{domxref("Comment", "comments")}}, from each other.

+ +

語法

+ +
var type = node.nodeType;
+
+ +

Returns an integer value which specifies the type of the node; possible values are listed in {{anch("Node type constants")}}.

+ +

常數

+ +

節點類型常數

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
{{domxref("Node.ELEMENT_NODE")}} {{readonlyinline}}1表示元素的 {{domxref("Element")}} 節點,如 {{HTMLElement("body")}}、{{HTMLElement("a")}}、{{HTMLElement("p")}}、{{HTMLElement("script")}}、{{HTMLElement("style")}}、{{HTMLElement("html")}}、{{HTMLElement("h1")}} 或 {{HTMLElement("div")}}
{{domxref("Node.TEXT_NODE")}} {{readonlyinline}}3於表示元素的 {{domxref("Element")}} 節點或表示 {{Glossary("attribute", "HTML 元素屬性")}}的 {{domxref("Attr")}} 節點中,表示了實際文字字元的 {{domxref("Text")}} 節點,它包括了換行與空格。
{{domxref("Node.PROCESSING_INSTRUCTION_NODE")}} {{readonlyinline}}7A {{domxref("ProcessingInstruction")}} of an XML document such as <?xml-stylesheet ... ?> declaration.
{{domxref("Node.COMMENT_NODE")}} {{readonlyinline}}8表示註解的 {{domxref("Comment")}} 節點。
{{domxref("Node.DOCUMENT_NODE")}} {{readonlyinline}}9表示文件的 {{domxref("Document")}} 節點。
{{domxref("Node.DOCUMENT_TYPE_NODE")}} {{readonlyinline}}10表示文件類型的 {{domxref("DocumentType")}} 節點,例如 HTML5 的 <!DOCTYPE html>
{{domxref("Node.DOCUMENT_FRAGMENT_NODE")}} {{readonlyinline}}11A {{domxref("DocumentFragment")}} node.
+ +

已過時的節點類型常數 {{deprecated_inline()}}

+ +

The following constants have been deprecated and should not be used anymore.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
Node.ATTRIBUTE_NODE2An {{domxref("Attr", "Attribute")}} of an {{domxref("Element")}}. The element attributes are no longer implementing the {{domxref("Node")}} interface in {{SpecName("DOM4")}} specification.
Node.CDATA_SECTION_NODE4A {{domxref("CDATASection")}}. Removed in {{SpecName("DOM4")}} specification.
Node.ENTITY_REFERENCE_NODE5An XML Entity Reference node. Removed in {{SpecName("DOM4")}} specification.
Node.ENTITY_NODE6An XML <!ENTITY ...> node. Removed in {{SpecName("DOM4")}} specification.
Node.NOTATION_NODE12An XML <!NOTATION ...> node. Removed in {{SpecName("DOM4")}} specification.
+ +

範例

+ +

Different types of nodes

+ +
document.nodeType === Node.DOCUMENT_NODE; // true
+document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true
+
+var fragment = document.createDocumentFragment();
+fragment.nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true
+
+var p = document.createElement("p");
+p.textContent = "Once upon a time...";
+
+p.nodeType === Node.ELEMENT_NODE; // true
+p.firstChild.nodeType === Node.TEXT_NODE; // true
+
+ +

Comments

+ +

This example checks if the first node inside the document element is a comment node, and if it is not, displays a message.

+ +
var node = document.documentElement.firstChild;
+if (node.nodeType != Node.COMMENT_NODE)
+  console.log("You should comment your code well!");
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-node-nodetype', 'Node.nodeType')}}{{Spec2('DOM WHATWG')}}Deprecated ATTRIBUTE_NODE, CDATA_SECTION_NODE, ENTITY_REFERENCE_NODE and NOTATION_NODE types.
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node.nodeType')}}{{Spec2('DOM3 Core')}}No changes.
{{SpecName('DOM2 Core', 'core.html#ID-111237558', 'Node.nodeType')}}{{Spec2('DOM2 Core')}}No changes.
{{SpecName('DOM1', 'level-one-core.html#ID-111237558', 'Node.nodeType')}}{{Spec2('DOM1')}}Initial definition.
diff --git a/files/zh-tw/web/api/node/ownerdocument/index.html b/files/zh-tw/web/api/node/ownerdocument/index.html new file mode 100644 index 0000000000..33e8e641e8 --- /dev/null +++ b/files/zh-tw/web/api/node/ownerdocument/index.html @@ -0,0 +1,111 @@ +--- +title: Node.ownerDocument +slug: Web/API/Node/ownerDocument +translation_of: Web/API/Node/ownerDocument +--- +
{{APIRef("DOM")}}
+ +

Node.ownerDocument 唯讀屬性會回傳一個此節點所屬的的頂層 document 物件。

+ +

語法

+ +
document = element.ownerDocument
+
+ + + +

範例

+ +
// given a node "p", get the top-level HTML child
+// of the document object
+
+var d = p.ownerDocument;
+var html = d.documentElement;
+
+ +

備註

+ +

The document object returned by this property is the main object with which all the child nodes in the actual HTML document are created. If this property is used on a node that is itself a document, the result is null.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM4", "#dom-node-ownerdocument", "Node.ownerDocument")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]6.0[2]{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Starting in Gecko 9.0 {{geckoRelease("9.0")}}, the ownerDocument of doctype nodes (that is, nodes for which {{domxref("Node.nodeType")}} is Node.DOCUMENT_TYPE_NODE or 10) is no longer null. Instead, the ownerDocument is the document on which document.implementation.createDocumentType() was called.

+ +

[2] http://msdn.microsoft.com/en-us/library/ie/ms534315(v=vs.85).aspx

diff --git a/files/zh-tw/web/api/node/removechild/index.html b/files/zh-tw/web/api/node/removechild/index.html new file mode 100644 index 0000000000..d453835c0c --- /dev/null +++ b/files/zh-tw/web/api/node/removechild/index.html @@ -0,0 +1,133 @@ +--- +title: Node.removeChild() +slug: Web/API/Node/removeChild +translation_of: Web/API/Node/removeChild +--- +
{{APIRef("DOM")}}
+ +

Node.removeChild() 方法從 DOM 移除一個子節點,並傳回移除的節點。

+ +

語法

+ +
var oldChild = node.removeChild(child);
+
+node.removeChild(child);
+
+ + + +

被刪除的子節點仍然存於記憶體之中,只是不在 DOM 了。從上述的第一種語法形式中,我們知道,透過引用 oldChild 還是可以在程式中重新使用已經被移除的子節點。

+ +

而第二種語法形式,因為沒有保留 oldChild 引用,因此假設你並沒有在其他地方保留節點引用,則它會立即無法使用且不可挽回,而且通常會在短時間內從內存管理中被自動刪除。

+ +

如果 child 並非某 element 節點的子元素,則此方法會拋出異常。而如果調用此方法時,child 雖是某 element 的子元素,但在嘗試刪除它的過程中已被其他事件處理程序刪除,也會拋出異常(例如 {{Event("blur")}})。

+ +

會丟出的錯誤

+ +

兩種不同的方式拋出異常:

+ +
    +
  1. +

    如果 child 確實是 element 的子元素且確實存在於 DOM,但已被刪除,則會丟出以下異常:

    + +

    Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

    +
  2. +
  3. +

    如果 child 不存在於頁面的 DOM,則會拋出下列的異常:
    +
    + Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

    +
  4. +
+ +

例子

+ +

簡單的例子

+ +

HTML:

+ +
<div id="top">
+  <div id="nested"></div>
+</div>
+
+ +

在知道父節點的情況下,刪除特定元素:

+ +
let d = document.getElementById("top");
+let d_nested = document.getElementById("nested");
+let throwawayNode = d.removeChild(d_nested);
+
+ +

沒有指定父節點的情況下,刪除特定元素:

+ +
let node = document.getElementById("nested");
+if (node.parentNode) {
+  node.parentNode.removeChild(node);
+}
+
+ +

從一個元素中移除所有子元素:

+ +
let element = document.getElementById("top");
+while (element.firstChild) {
+  element.removeChild(element.firstChild);
+}
+
+ +

造成一個TypeError

+ +
<!--Sample HTML code-->
+<div id="top"> </div>
+
+<script type="text/javascript">
+  let top = document.getElementById("top");
+  let nested = document.getElementById("nested");
+
+  // Throws Uncaught TypeError
+  let garbage = top.removeChild(nested);
+</script>
+
+ +

造成一個NotFoundError

+ +
<!--Sample HTML code-->
+<div id="top">
+  <div id="nested"></div>
+</div>
+
+<script type="text/javascript">
+  let top = document.getElementById("top");
+  let nested = document.getElementById("nested");
+
+  // This first call correctly removes the node
+  let garbage = top.removeChild(nested);
+
+  // Throws Uncaught NotFoundError
+  garbage = top.removeChild(nested);
+</script>
+
+ +

規範

+ + + +

瀏覽器相容性

+ + + +

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

+ +

相關連結

+ + diff --git a/files/zh-tw/web/api/node/textcontent/index.html b/files/zh-tw/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..9375396158 --- /dev/null +++ b/files/zh-tw/web/api/node/textcontent/index.html @@ -0,0 +1,158 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +

Node.textContent 屬性表示了節點或其後代的文字內容。

+ +

語法

+ +
var text = element.textContent;
+element.textContent = "this is some sample text";
+
+ +

描述

+ + + +

與 innerText 的差異

+ +

Internet Explorer introduced element.innerText. The intention is similar but with the following differences:

+ + + +

innerHTML 的差異

+ +

innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.

+ +

範例

+ +
// Given the following HTML fragment:
+//   <div id="divA">This is <span>some</span> text</div>
+
+// Get the text content:
+var text = document.getElementById("divA").textContent;
+// |text| is set to "This is some text".
+
+// Set the text content:
+document.getElementById("divA").textContent = "This is some text";
+// The HTML for divA is now:
+//   <div id="divA">This is some text</div>
+
+ +

Polyfill for IE8

+ +
if (Object.defineProperty
+  && Object.getOwnPropertyDescriptor
+  && Object.getOwnPropertyDescriptor(Element.prototype, "textContent")
+  && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
+  (function() {
+    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
+    Object.defineProperty(Element.prototype, "textContent",
+     {
+       get: function() {
+         return innerText.get.call(this);
+       },
+       set: function(s) {
+         return innerText.set.call(this, s);
+       }
+     }
+   );
+  })();
+}
+
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1+299.64 (possibly earlier)3 (possibly earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}No changes versus DOM4
{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM4')}} 
{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}}{{Spec2('DOM3 Core')}}Introduced
+ +

參見

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