aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/api/nodelist/index.html
blob: a31cc6261515d6cb395a2b5c1432fb06de948445 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
---
title: NodeList
slug: Web/API/NodeList
translation_of: Web/API/NodeList
---
<div>{{APIRef("DOM")}}</div>

<p><strong><code>NodeList</code></strong> 物件是節點的集合,可藉由 {{domxref("Node.childNodes")}} 屬性以及 {{domxref("document.querySelectorAll()")}} 方法取得。</p>

<div class="note">
<p>雖然 <code>NodeList</code> 不是 <code>Array</code>,但仍可以使用 <code>forEach()</code> 方法來進行迭代。一些老舊瀏覽器並未實作此方法。</p>
</div>

<p>在某些情況下,<code>NodeList</code><em>動態集合(live collection)</em>,意思是 DOM 的改變會反映於集合。例如,{{domxref("Node.childNodes")}} 便是即時更新(live)的:</p>

<pre class="brush: js">var parent = document.getElementById('parent');
var child_nodes = parent.childNodes;
console.log(child_nodes.length); // let's assume "2"
parent.appendChild(document.createElement('div'));
console.log(child_nodes.length); // should output "3"
</pre>

<p>在其他的情況下,<code>NodeList</code> 是一個<em>靜態的集合(static collection)</em>,代表任何之後的 DOM 變化都不會影響集合的內容。{{domxref("document.querySelectorAll()")}} 會回傳一個靜態的 <code>NodeList</code></p>

<p>當你要選擇如何迭代 <code>NodeList</code> 中的項目時,最好能於心中區分動態與靜態集合,尤其是在取得集合長度(length of the list)的時候。</p>

<h2 id="屬性">屬性</h2>

<dl>
 <dt>{{domxref("NodeList.length")}}</dt>
 <dd>The number of nodes in the <code>NodeList</code>.</dd>
</dl>

<h2 id="方法">方法</h2>

<dl>
 <dt>{{domxref("NodeList.item()")}}</dt>
 <dd>Returns an item in the list by its index, or <code>null</code> if the index is out-of-bounds; can be used as an alternative to simply accessing <code>nodeList[idx]</code> (which instead returns  <code>undefined</code> when <code>idx</code> is out-of-bounds).</dd>
 <dt>{{domxref("NodeList.entries()")}}</dt>
 <dd>Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.</dd>
 <dt>{{domxref("NodeList.forEach()")}}</dt>
 <dd>Executes a provided function once per <code>NodeList</code> element.</dd>
 <dt>{{domxref("NodeList.keys()")}}</dt>
 <dd>Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all keys of the key/value pairs contained in this object.</dd>
 <dt>{{domxref("NodeList.values()")}}</dt>
 <dd>Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all values of the key/value pairs contained in this object.</dd>
</dl>

<h2 id="範例">範例</h2>

<p>It's possible to loop over the items in a <code>NodeList</code> using:</p>

<pre class="brush: js">for (var i = 0; i &lt; myNodeList.length; ++i) {
  var item = myNodeList[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
}
</pre>

<p>Don't be tempted to use <code><a href="/en-US/docs/JavaScript/Reference/Statements/for...in" title="JavaScript/ Reference/Statements/for...in">for...in</a></code> or <code><a href="/en-US/docs/JavaScript/Reference/Statements/for_each...in" title="JavaScript/ Reference/Statements/for each...in">for each...in</a></code> to enumerate the items in the list, since that will also enumerate the length and item properties of the <code>NodeList</code> and cause errors if your script assumes it only has to deal with {{domxref("element")}} objects. Also, <code>for..in</code> is not guaranteed to visit the properties in any particular order.</p>

<p><code><a href="/en-US/docs/JavaScript/Reference/Statements/for...of" title="/en-US/docs/JavaScript/Reference/Statements/for...of">for...of</a></code> loops will loop over <code>NodeList</code> objects correctly:</p>

<pre class="brush: js">var list = document.querySelectorAll( 'input[type=checkbox]' );
for (var item of list) {
  item.checked = true;
}</pre>

<p>Recent browsers also support iterator methods, {{domxref("NodeList.forEach()", "forEach()")}}, as well as {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, and {{domxref("NodeList.keys()", "keys()")}}</p>

<p>There is also an Internet Explorer compatible way to use {{jsxref("Array.forEach()", "Array.prototype.forEach")}} for iteration.</p>

<pre class="brush: js">var list = document.querySelectorAll( 'input[type=checkbox]' );
Array.prototype.forEach.call(list, function (item) {
  item.checked = true;
});</pre>

<h2 id="Specifications" name="Specifications">NodeList 原型</h2>

<p>You can also add prototypes to nodelist:</p>

<pre class="brush: js">var elements = document.querySelectorAll(".suggestions");

NodeList.prototype.addEventListener = function(event, func) {
    this.forEach(function(content, item) {
       content.addEventListener(event, func);
    });
}

function log() {
    console.log(this, " was clicked");
}

elements.addEventListener("click", log);
//or
elements.addEventListener("click", function() {
    console.log(this, "  awas clicked");
});
// output from both will be <em>element </em>was clicked the element would be HTML Element</pre>

<p>For information about forEach see <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" title="Web/JavaScript/Reference/Global_Objects/Array/forEach">Array.prototype.forEach()</a></p>

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

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}</td>
   <td>{{ Spec2('DOM WHATWG') }}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('DOM4', '#interface-nodelist', 'NodeList')}}</td>
   <td>{{ Spec2('DOM4') }}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('DOM3 Core', 'core.html#ID-536297177', 'NodeList')}}</td>
   <td>{{ Spec2('DOM3 Core') }}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('DOM2 Core', 'core.html#ID-536297177', 'NodeList')}}</td>
   <td>{{ Spec2('DOM2 Core') }}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('DOM1', 'level-one-core.html#ID-536297177', 'NodeList')}}</td>
   <td>{{ Spec2('DOM1') }}</td>
   <td>Initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="瀏覽器相容性">瀏覽器相容性</h2>

{{Compat("api.NodeList")}}