aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/api/node/childnodes/index.html
blob: a828bd781bfedb2677e4b3b4fcb337ae89ab5b56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
---
title: Node.childNodes
slug: Web/API/Node/childNodes
translation_of: Web/API/Node/childNodes
---
<div>
<div>{{APIRef("DOM")}}</div>
</div>

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

<h2 id="Syntax" name="Syntax">語法</h2>

<pre class="syntaxbox">var <var>ndList</var> = elementNodeReference.childNodes;
</pre>

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

<p>範例</p>

<pre class="brush:js">// parg is an object reference to a &lt;p&gt; element

// First check that the element has child nodes
if (parg.hasChildNodes()) {
  var children = parg.childNodes;

  for (var i = 0; i &lt; children.length; i++) {
    // do something with each child as children[i]
    // NOTE: List is live, adding or removing children will change the list
  }
}</pre>

<hr>
<pre class="brush:js">// 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);
}</pre>

<h2 id="Notes" name="Notes">備註</h2>

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

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

<p><code>childNodes</code> 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.</p>

<h2 id="Specification" name="Specification">規範</h2>

<ul>
 <li><a class="external" href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1451460987">W3C DOM 2 Core: childNodes</a></li>
 <li><a class="external" href="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-1451460987">W3C DOM 3 Core: childNodes</a></li>
 <li><a class="external" href="http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-536297177">W3C DOM 3 NodeList interface</a></li>
</ul>

<h2 id="See_also" name="See_also">參見</h2>

<ul>
 <li>{{ domxref("Node.firstChild") }}</li>
 <li>{{ domxref("Node.lastChild") }}</li>
 <li>{{ domxref("Node.nextSibling") }}</li>
 <li>{{ domxref("Node.previousSibling") }}</li>
 <li>{{ domxref("ParentNode.children") }}</li>
</ul>