UNPKG

51.3 kBMarkdownView Raw
1# d3-selection
2
3Selections allow powerful data-driven transformation of the document object model (DOM): set [attributes](#selection_attr), [styles](#selection_style), [properties](#selection_property), [HTML](#selection_html) or [text](#selection_text) content, and more. Using the [data join](#joining-data)’s [enter](#selection_enter) and [exit](#selection_enter) selections, you can also [add](#selection_append) or [remove](#selection_remove) elements to correspond to data.
4
5Selection methods typically return the current selection, or a new selection, allowing the concise application of multiple operations on a given selection via method chaining. For example, to set the class and color style of all paragraph elements in the current document:
6
7```js
8d3.selectAll("p")
9 .attr("class", "graf")
10 .style("color", "red");
11```
12
13This is equivalent to:
14
15```js
16var p = d3.selectAll("p");
17p.attr("class", "graf");
18p.style("color", "red");
19```
20
21By convention, selection methods that return the current selection use *four* spaces of indent, while methods that return a new selection use only *two*. This helps reveal changes of context by making them stick out of the chain:
22
23```js
24d3.select("body")
25 .append("svg")
26 .attr("width", 960)
27 .attr("height", 500)
28 .append("g")
29 .attr("transform", "translate(20,20)")
30 .append("rect")
31 .attr("width", 920)
32 .attr("height", 460);
33```
34
35Selections are immutable. All selection methods that affect which elements are selected (or their order) return a new selection rather than modifying the current selection. However, note that elements are necessarily mutable, as selections drive transformations of the document!
36
37## Installing
38
39If you use NPM, `npm install d3-selection`. Otherwise, download the [latest release](https://github.com/d3/d3-selection/releases/latest). You can also load directly from [d3js.org](https://d3js.org), either as a [standalone library](https://d3js.org/d3-selection.v1.min.js) or as part of [D3 4.0](https://github.com/d3/d3). AMD, CommonJS, and vanilla environments are supported. In vanilla, a `d3` global is exported:
40
41```html
42<script src="https://d3js.org/d3-selection.v1.min.js"></script>
43<script>
44
45var div = d3.selectAll("div");
46
47</script>
48```
49
50[Try d3-selection in your browser.](https://tonicdev.com/npm/d3-selection)
51
52## API Reference
53
54* [Selecting Elements](#selecting-elements)
55* [Modifying Elements](#modifying-elements)
56* [Joining Data](#joining-data)
57* [Handling Events](#handling-events)
58* [Control Flow](#control-flow)
59* [Local Variables](#local-variables)
60* [Namespaces](#namespaces)
61
62### Selecting Elements
63
64Selection methods accept [W3C selector strings](http://www.w3.org/TR/selectors-api/) such as `.fancy` to select elements with the class *fancy*, or `div` to select DIV elements. Selection methods come in two forms: select and selectAll: the former selects only the first matching element, while the latter selects all matching elements in document order. The top-level selection methods, [d3.select](#select) and [d3.selectAll](#selectAll), query the entire document; the subselection methods, [*selection*.select](#selection_select) and [*selection*.selectAll](#selection_selectAll), restrict selection to descendants of the selected elements.
65
66<a name="selection" href="#selection">#</a> d3.<b>selection</b>()
67
68[Selects](#select) the root element, `document.documentElement`. This function can also be used to test for selections (`instanceof d3.selection`) or to extend the selection prototype. For example, to add a method to check checkboxes:
69
70```js
71d3.selection.prototype.checked = function(value) {
72 return arguments.length < 1
73 ? this.property("checked")
74 : this.property("checked", !!value);
75};
76```
77
78And then to use:
79
80```js
81d3.selectAll("input[type=checkbox]").checked(true);
82```
83
84<a name="select" href="#select">#</a> d3.<b>select</b>(<i>selector</i>)
85
86Selects the first element that matches the specified *selector* string. If no elements match the *selector*, returns an empty selection. If multiple elements match the *selector*, only the first matching element(in document order will be selected. For example, to select the first anchor element:
87
88```js
89var anchor = d3.select("a");
90```
91
92If the *selector* is not a string, instead selects the specified node; this is useful if you already have a reference to a node, such as `this` within an event listener or a global such as `document.body`. For example, to make a clicked paragraph red:
93
94```js
95d3.selectAll("p").on("click", function() {
96 d3.select(this).style("color", "red");
97});
98```
99
100<a name="selectAll" href="#selectAll">#</a> d3.<b>selectAll</b>(<i>selector</i>)
101
102Selects all elements that match the specified *selector* string. The elements will be selected in document order (top-to-bottom). If no elements in the document match the *selector*, or if the *selector* is null or undefined, returns an empty selection. For example, to select all paragraphs:
103
104```js
105var paragraph = d3.selectAll("p");
106```
107
108If the *selector* is not a string, instead selects the specified array of nodes; this is useful if you already have a reference to nodes, such as `this.childNodes` within an event listener or a global such as `document.links`. The nodes may instead be a pseudo-array such as a `NodeList` or `arguments`. For example, to color all links red:
109
110```js
111d3.selectAll(document.links).style("color", "red");
112```
113
114<a name="selection_select" href="#selection_select">#</a> <i>selection</i>.<b>select</b>(<i>selector</i>)
115
116For each selected element, selects the first descendant element that matches the specified *selector* string. If no element matches the specified selector for the current element, the element at the current index will be null in the returned selection. (If the *selector* is null, every element in the returned selection will be null, resulting in an empty selection.) If the current element has associated data, this data is propagated to the corresponding selected element. If multiple elements match the selector, only the first matching element in document order is selected. For example, to select the first bold element in every paragraph:
117
118```js
119var b = d3.selectAll("p").select("b");
120```
121
122If the *selector* is a function, it is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. It must return an element, or null if there is no matching element. For example, to select the previous sibling of each paragraph:
123
124```js
125var previous = d3.selectAll("p").select(function() {
126 return this.previousElementSibling;
127});
128```
129
130Unlike [*selection*.selectAll](#selection_selectAll), *selection*.select does not affect grouping: it preserves the existing group structure and indexes, and propagates data (if any) to selected children. Grouping plays an important role in the [data join](#joining-data). See [Nested Selections](http://bost.ocks.org/mike/nest/) and [How Selections Work](http://bost.ocks.org/mike/selection/) for more on this topic.
131
132<a name="selection_selectAll" href="#selection_selectAll">#</a> <i>selection</i>.<b>selectAll</b>(<i>selector</i>)
133
134For each selected element, selects the descendant elements that match the specified *selector* string. The elements in the returned selection are grouped by their corresponding parent node in this selection. If no element matches the specified selector for the current element, or if the *selector* is null, the group at the current index will be empty. The selected elements do not inherit data from this selection; use [*selection*.data](#selection_data) to propagate data to children. For example, to select the bold elements in every paragraph:
135
136```js
137var b = d3.selectAll("p").selectAll("b");
138```
139
140If the *selector* is a function, it is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. It must return an array of elements (or a pseudo-array, such as a NodeList), or the empty array if there are no matching elements. For example, to select the previous and next siblings of each paragraph:
141
142```js
143var sibling = d3.selectAll("p").selectAll(function() {
144 return [
145 this.previousElementSibling,
146 this.nextElementSibling
147 ];
148});
149```
150
151Unlike [*selection*.select](#selection_select), *selection*.selectAll does affect grouping: each selected descendant is grouped by the parent element in the originating selection. Grouping plays an important role in the [data join](#joining-data). See [Nested Selections](http://bost.ocks.org/mike/nest/) and [How Selections Work](http://bost.ocks.org/mike/selection/) for more on this topic.
152
153<a name="selection_filter" href="#selection_filter">#</a> <i>selection</i>.<b>filter</b>(<i>filter</i>)
154
155Filters the selection, returning a new selection that contains only the elements for which the specified *filter* is true. The *filter* may be specified either as a selector string or a function. If a function, it is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element.
156
157For example, to filter a selection of table rows to contain only even rows:
158
159```js
160var even = d3.selectAll("tr").filter(":nth-child(even)");
161```
162
163This is approximately equivalent to using [d3.selectAll](#selectAll) directly, although the indexes may be different:
164
165```js
166var even = d3.selectAll("tr:nth-child(even)");
167```
168
169Similarly, using a function:
170
171```js
172var even = d3.selectAll("tr").filter(function(d, i) { return i & 1; });
173```
174
175Or using [*selection*.select](#selection_select):
176
177```js
178var even = d3.selectAll("tr").select(function(d, i) { return i & 1 ? this : null; });
179```
180
181Note that the `:nth-child` pseudo-class is a one-based index rather than a zero-based index. Also, the above filter functions do not have precisely the same meaning as `:nth-child`; they rely on the selection index rather than the number of preceeding sibling elements in the DOM.
182
183The returned filtered selection preserves the parents of this selection, but like [*array*.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), it does not preserve indexes as some elements may be removed; use [*selection*.select](#selection_select) to preserve the index, if needed.
184
185<a name="selection_merge" href="#selection_merge">#</a> <i>selection</i>.<b>merge</b>(<i>other</i>)
186
187Returns a new selection merging this selection with the specified *other* selection. The returned selection has the same number of groups and the same parents as this selection. Any missing (null) elements in this selection are filled with the corresponding element, if present (not null), from the specified *selection*. (If the *other* selection has additional groups or parents, they are ignored.)
188
189This method is commonly used to merge the [enter](#selection_enter) and [update](#selection_data) selections after a [data-join](#joining-data). After modifying the entering and updating elements separately, you can merge the two selections and perform operations on both without duplicate code. For example:
190
191```js
192var circle = svg.selectAll("circle").data(data) // UPDATE
193 .style("fill", "blue");
194
195circle.exit().remove(); // EXIT
196
197circle.enter().append("circle") // ENTER
198 .style("fill", "green")
199 .merge(circle) // ENTER + UPDATE
200 .style("stroke", "black");
201```
202
203This method is not intended for concatenating arbitrary selections, however: if both this selection and the specified *other* selection have (non-null) elements at the same index, this selection’s element is returned in the merge and the *other* selection’s element is ignored.
204
205<a name="matcher" href="#matcher">#</a> d3.<b>matcher</b>(<i>selector</i>)
206
207Given the specified *selector*, returns a function which returns true if `this` element [matches](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches) the specified selector. This method is used internally by [*selection*.filter](#selection_filter). For example, this:
208
209```js
210var div = selection.filter("div");
211```
212
213Is equivalent to:
214
215```js
216var div = selection.filter(d3.matcher("div"));
217```
218
219(Although D3 is not a compatibility layer, this implementation does support vendor-prefixed implementations due to the recent standardization of *element*.matches.)
220
221<a name="selector" href="#selector">#</a> d3.<b>selector</b>(<i>selector</i>)
222
223Given the specified *selector*, returns a function which returns the first descendant of `this` element that matches the specified selector. This method is used internally by [*selection*.select](#selection_select). For example, this:
224
225```js
226var div = selection.select("div");
227```
228
229Is equivalent to:
230
231```js
232var div = selection.select(d3.selector("div"));
233```
234
235<a name="selectorAll" href="#selectorAll">#</a> d3.<b>selectorAll</b>(<i>selector</i>)
236
237Given the specified *selector*, returns a function which returns all descendants of `this` element that match the specified selector. This method is used internally by [*selection*.selectAll](#selection_selectAll). For example, this:
238
239```js
240var div = selection.selectAll("div");
241```
242
243Is equivalent to:
244
245```js
246var div = selection.selectAll(d3.selectorAll("div"));
247```
248
249<a name="window" href="#window">#</a> d3.<b>window</b>(<i>node</i>)
250
251Returns the owner window for the specified *node*. If *node* is a node, returns the owner document’s default view; if *node* is a document, returns its default view; otherwise returns the *node*.
252
253### Modifying Elements
254
255After selecting elements, use the selection’s transformation methods to affect document content. For example, to set the name attribute and color style of an anchor element:
256
257```js
258d3.select("a")
259 .attr("name", "fred")
260 .style("color", "red");
261```
262
263To experiment with selections, visit [d3js.org](https://d3js.org) and open your browser’s developer console! (In Chrome, open the console with ⌥⌘J.) Select elements and then inspect the returned selection to see which elements are selected and how they are grouped. Call selection methods and see how the page content changes.
264
265<a name="selection_attr" href="#selection_attr">#</a> <i>selection</i>.<b>attr</b>(<i>name</i>[, <i>value</i>])
266
267If a *value* is specified, sets the attribute with the specified *name* to the specified value on the selected elements and returns this selection. If the *value* is a constant, all elements are given the same attribute value; otherwise, if the *value* is a function, the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function’s return value is then used to set each element’s attribute. A null value will remove the specified attribute.
268
269If a *value* is not specified, returns the current value of the specified attribute for the first (non-null) element in the selection. This is generally useful only if you know that the selection contains exactly one element.
270
271The specified *name* may have a namespace prefix, such as `xlink:href` to specify the `href` attribute in the XLink namespace. See [namespaces](#namespaces) for the map of supported namespaces; additional namespaces can be registered by adding to the map.
272
273<a name="selection_classed" href="#selection_classed">#</a> <i>selection</i>.<b>classed</b>(<i>names</i>[, <i>value</i>])
274
275If a *value* is specified, assigns or unassigns the specified CSS class *names* on the selected elements by setting the `class` attribute or modifying the `classList` property and returns this selection. The specified *names* is a string of space-separated class names. For example, to assign the classes `foo` and `bar` to the selected elements:
276
277```js
278selection.classed("foo bar", true);
279```
280
281If the *value* is truthy, then all elements are assigned the specified classes; otherwise, the classes are unassigned. If the *value* is a function, then the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function’s return value is then used to assign or unassign classes on each element. For example, to randomly associate the class *foo* with on average half the selected elements:
282
283```js
284selection.classed("foo", function() { return Math.random(); });
285```
286
287If a *value* is not specified, returns true if and only if the first (non-null) selected element has the specified *classes*. This is generally useful only if you know the selection contains exactly one element.
288
289<a name="selection_style" href="#selection_style">#</a> <i>selection</i>.<b>style</b>(<i>name</i>[, <i>value</i>[, <i>priority</i>]])
290
291If a *value* is specified, sets the style property with the specified *name* to the specified value on the selected elements and returns this selection. If the *value* is a constant, then all elements are given the same style property value; otherwise, if the *value* is a function, then the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function’s return value is then used to set each element’s style property. A null value will remove the style property. An optional *priority* may also be specified, either as null or the string `important` (without the exclamation point).
292
293If a *value* is not specified, returns the current computed value of the specified style property for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element. The computed value **may be different than the previously-set value**, particularly if it was set using a shorthand property (such as the `font` style, which is shorthand for `font-size`, `font-face`, etc.).
294
295Caution: unlike many SVG attributes, CSS styles typically have associated units. For example, `3px` is a valid stroke-width property value, while `3` is not. Some browsers implicitly assign the `px` (pixel) unit to numeric values, but not all browsers do: IE, for example, throws an “invalid arguments” error!
296
297<a name="selection_property" href="#selection_property">#</a> <i>selection</i>.<b>property</b>(<i>name</i>[, <i>value</i>])
298
299Some HTML elements have special properties that are not addressable using attributes or styles, such as a form field’s text `value` and a checkbox’s `checked` boolean. Use this method to get or set these properties.
300
301If a *value* is specified, sets the property with the specified *name* to the specified value on selected elements. If the *value* is a constant, then all elements are given the same property value; otherwise, if the *value* is a function, then the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function’s return value is then used to set each element’s property. A null value will delete the specified property.
302
303If a *value* is not specified, returns the value of the specified property for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.
304
305<a name="selection_text" href="#selection_text">#</a> <i>selection</i>.<b>text</b>([<i>value</i>])
306
307If a *value* is specified, sets the [text content](http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent) to the specified value on all selected elements, replacing any existing child elements. If the *value* is a constant, then all elements are given the same text content; otherwise, if the *value* is a function, then the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function’s return value is then used to set each element’s text content. A null value will clear the content.
308
309If a *value* is not specified, returns the text content for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.
310
311<a name="selection_html" href="#selection_html">#</a> <i>selection</i>.<b>html</b>([<i>value</i>])
312
313If a *value* is specified, sets the [inner HTML](http://dev.w3.org/html5/spec-LC/apis-in-html-documents.html#innerhtml) to the specified value on all selected elements, replacing any existing child elements. If the *value* is a constant, then all elements are given the same inner HTML; otherwise, if the *value* is a function, then the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function’s return value is then used to set each element’s inner HTML. A null value will clear the content.
314
315If a *value* is not specified, returns the inner HTML for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.
316
317Use [*selection*.append](#selection_append) or [*selection*.insert](#selection_insert) instead to create data-driven content; this method is intended for when you want a little bit of HTML, say for rich formatting. Also, *selection*.html is only supported on HTML elements. SVG elements and other non-HTML elements do not support the innerHTML property, and thus are incompatible with *selection*.html. Consider using [XMLSerializer](https://developer.mozilla.org/en-US/docs/XMLSerializer) to convert a DOM subtree to text. See also the [innersvg polyfill](https://code.google.com/p/innersvg/), which provides a shim to support the innerHTML property on SVG elements.
318
319<a name="selection_append" href="#selection_append">#</a> <i>selection</i>.<b>append</b>(<i>type</i>)
320
321If the specified *type* is a string, appends a new element of this type (tag name) as the last child of each selected element, or the next following sibling in the update selection if this is an [enter selection](#selection_enter). (The enter behavior allows you to insert elements into the DOM in an order consistent with bound data; however, the slower [*selection*.order](#selection_order) may still be required if updating elements change order.) Otherwise, the *type* may be a function which is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. This function should return an element to be appended. (The function typically creates a new element, but it may instead return an existing element.) For example, to append a DIV element to each paragraph:
322
323```js
324d3.selectAll("p").append("div");
325```
326
327This is equivalent to:
328
329```js
330d3.selectAll("p").append(function() {
331 return document.createElement("div");
332});
333```
334
335Which is equivalent to:
336
337```js
338d3.selectAll("p").select(function() {
339 return this.appendChild(document.createElement("div"));
340});
341```
342
343In both cases, this method returns a new selection containing the appended elements. Each new element inherits the data of the current elements, if any, in the same manner as [*selection*.select](#selection_select).
344
345The specified *name* may have a namespace prefix, such as `svg:text` to specify a `text` attribute in the SVG namespace. See [namespaces](#namespaces) for the map of supported namespaces; additional namespaces can be registered by adding to the map. If no namespace is specified, the namespace will be inherited from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used (for example, `svg` implies `svg:svg`).
346
347<a name="selection_insert" href="#selection_insert">#</a> <i>selection</i>.<b>insert</b>(<i>type</i>, <i>before</i>)
348
349If the specified *type* is a string, inserts a new element of this type (tag name) before the element matching the specified *before* selector for each selected element. For example, a *before* selector `:first-child` will prepend nodes before the first child. Both *type* and *before* may instead be specified as functions which are evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The *type* function should return an element to be inserted; the *before* function should return the child element before which the element should be inserted. For example, to insert a DIV element to each paragraph:
350
351```js
352d3.selectAll("p").insert("div");
353```
354
355This is equivalent to:
356
357```js
358d3.selectAll("p").insert(function() {
359 return document.createElement("div");
360});
361```
362
363Which is equivalent to:
364
365```js
366d3.selectAll("p").select(function() {
367 return this.insertBefore(document.createElement("div"), null);
368});
369```
370
371In both cases, this method returns a new selection containing the appended elements. Each new element inherits the data of the current elements, if any, in the same manner as [*selection*.select](#selection_select).
372
373The specified *name* may have a namespace prefix, such as `svg:text` to specify a `text` attribute in the SVG namespace. See [namespaces](#namespaces) for the map of supported namespaces; additional namespaces can be registered by adding to the map. If no namespace is specified, the namespace will be inherited from the parent element; or, if the name is one of the known prefixes, the corresponding namespace will be used (for example, `svg` implies `svg:svg`).
374
375<a name="selection_remove" href="#selection_remove">#</a> <i>selection</i>.<b>remove</b>()
376
377Removes the selected elements from the document. Returns this selection (the removed elements) which are now detached from the DOM. There is not currently a dedicated API to add removed elements back to the document; however, you can pass a function to [*selection*.append](#selection_append) or [*selection*.insert](#selection_insert) to re-add elements.
378
379<a name="selection_sort" href="#selection_sort">#</a> <i>selection</i>.<b>sort</b>(<i>compare</i>)
380
381Returns a new selection that contains a copy of each group in this selection sorted according to the *compare* function. After sorting, re-inserts elements to match the resulting order (per [*selection*.order](#selection_order)).
382
383The compare function, which defaults to [ascending](https://github.com/d3/d3-array#ascending), is passed two elements’ data *a* and *b* to compare. It should return either a negative, positive, or zero value. If negative, then *a* should be before *b*; if positive, then *a* should be after *b*; otherwise, *a* and *b* are considered equal and the order is arbitrary.
384
385Note that sorting is not guaranteed to be stable; however, it is guaranteed to have the same behavior as your browser’s built-in [sort](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) method on arrays.
386
387<a name="selection_order" href="#selection_order">#</a> <i>selection</i>.<b>order</b>()
388
389Re-inserts elements into the document such that the document order of each group matches the selection order. This is equivalent to calling [*selection*.sort](#selection_sort) if the data is already sorted, but much faster.
390
391<a name="selection_raise" href="#selection_raise">#</a> <i>selection</i>.<b>raise</b>()
392
393Re-inserts each selected element, in order, as the last child of its parent. Equivalent to:
394
395```js
396selection.each(function() {
397 this.parentNode.appendChild(this);
398});
399```
400
401<a name="selection_lower" href="#selection_lower">#</a> <i>selection</i>.<b>lower</b>()
402
403Re-inserts each selected element, in order, as the first child of its parent. Equivalent to:
404
405```js
406selection.each(function() {
407 this.parentNode.insertBefore(this, this.parentNode.firstChild);
408});
409```
410
411<a name="creator" href="#creator">#</a> d3.<b>creator</b>(<i>name</i>)
412
413Given the specified element *name*, returns a function which creates an element of the given name, assuming that `this` is the parent element. This method is used internally by [*selection*.append](#selection_append) and [*selection*.insert](#selection_insert) to create new elements. For example, this:
414
415```js
416selection.append("div");
417```
418
419Is equivalent to:
420
421```js
422selection.append(d3.creator("div"));
423```
424
425See [namespace](#namespace) for details on supported namespace prefixes, such as for SVG elements.
426
427### Joining Data
428
429For an introduction to D3’s data joins, see [Thinking With Joins](http://bost.ocks.org/mike/join/). Also see the [General Update Pattern](http://bl.ocks.org/mbostock/3808218) examples.
430
431<a name="selection_data" href="#selection_data">#</a> <i>selection</i>.<b>data</b>([<i>data</i>[, <i>key</i>]])
432
433Joins the specified array of *data* with the selected elements, returning a new selection that it represents the *update* selection: the elements successfully bound to data. Also defines the [enter](#selection_enter) and [exit](#selection_exit) selections on the returned selection, which can be used to add or remove elements to correspond to the new data. The specified *data* is an array of arbitrary values (*e.g.*, numbers or objects), or a function that returns an array of values for each group. When data is assigned to an element, it is stored in the property `__data__`, thus making the data “sticky” and available on re-selection.
434
435The *data* is specified **for each group** in the selection. If the selection has multiple groups (such as [d3.selectAll](#selectAll) followed by [*selection*.selectAll](#selection_selectAll)), then *data* should typically be specified as a function. This function will be evaluated for each group in order, being passed the group’s parent datum (*d*, which may be undefined), the group index (*i*), and the selection’s parent nodes (*nodes*), with *this* as the group’s parent element. For example, to create an HTML table from a matrix of numbers:
436
437```js
438var matrix = [
439 [11975, 5871, 8916, 2868],
440 [ 1951, 10048, 2060, 6171],
441 [ 8010, 16145, 8090, 8045],
442 [ 1013, 990, 940, 6907]
443];
444
445var tr = d3.select("body")
446 .append("table")
447 .selectAll("tr")
448 .data(matrix)
449 .enter().append("tr");
450
451var td = tr.selectAll("td")
452 .data(function(d) { return d; })
453 .enter().append("td")
454 .text(function(d) { return d; });
455```
456
457In this example the *data* function is the identity function: for each table row, it returns the corresponding row from the data matrix.
458
459If a *key* function is not specified, then the first datum in *data* is assigned to the first selected element, the second datum to the second selected element, and so on. A *key* function may be specified to control which datum is assigned to which element, replacing the default join-by-index. This key function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The key function is then also evaluated for each new datum in *data*, being passed the current datum (*d*), the current index (*i*), and the group’s new *data*, with *this* as the group’s parent DOM element. The datum for a given key is assigned to the element with the matching key. If multiple elements have the same key, the duplicate elements are put into the exit selection; if multiple data have the same key, the duplicate data are put into the enter selection.
460
461For example, given this document:
462
463```html
464<div id="Ford"></div>
465<div id="Jarrah"></div>
466<div id="Kwon"></div>
467<div id="Locke"></div>
468<div id="Reyes"></div>
469<div id="Shephard"></div>
470```
471
472You could join data by key as follows:
473
474
475```js
476var data = [
477 {name: "Locke", number: 4},
478 {name: "Reyes", number: 8},
479 {name: "Ford", number: 15},
480 {name: "Jarrah", number: 16},
481 {name: "Shephard", number: 31},
482 {name: "Kwon", number: 34}
483];
484
485d3.selectAll("div")
486 .data(data, function(d) { return d ? d.name : this.id; })
487 .text(function(d) { return d.number; });
488```
489
490This example key function uses the datum *d* if present, and otherwise falls back to the element’s id property. Since these elements were not previously bound to data, the datum *d* is null when the key function is evaluated on selected elements, and non-null when the key function is evaluated on the new data.
491
492The *update* and *enter* selections are returned in data order, while the *exit* selection preserves the selection order prior to the join. If a key function is specified, the order of elements in the selection may not match their order in the document; use [*selection*.order](#order) or [*selection*.sort](#sort) as needed. For more on how the key function affects the join, see [A Bar Chart, Part 2](http://bost.ocks.org/mike/bar/2/) and [Object Constancy](http://bost.ocks.org/mike/constancy/).
493
494If *data* is not specified, this method returns the array of data for the selected elements.
495
496This method cannot be used to clear bound data; use [*selection*.datum](#selection_datum) instead.
497
498<a name="selection_enter" href="#selection_enter">#</a> <i>selection</i>.<b>enter</b>()
499
500Returns the enter selection: placeholder nodes for each datum that had no corresponding DOM element in the selection. The enter selection is determined by [*selection*.data](#selection_data), and is empty on a selection that is not joined to data.
501
502The enter selection is typically used to create “missing” elements corresponding to new data. For example, to create DIV elements from an array of numbers:
503
504```js
505var div = d3.select("body")
506 .selectAll("div")
507 .data([4, 8, 15, 16, 23, 42])
508 .enter().append("div")
509 .text(function(d) { return d; });
510```
511
512If the body is initially empty, the above code will create six new DIV elements, append them to the body in-order, and assign their text content as the associated (string-coerced) number:
513
514```html
515<div>4</div>
516<div>8</div>
517<div>15</div>
518<div>16</div>
519<div>23</div>
520<div>42</div>
521```
522
523Conceptually, the enter selection’s placeholders are pointers to the parent element (in this example, the document body). The enter selection is typically only used transiently to append elements, and is often [merged](#selection_merge) with the update selection after appending, such that modifications can be applied to both entering and updating elements.
524
525<a name="selection_exit" href="#selection_exit">#</a> <i>selection</i>.<b>exit</b>()
526
527Returns the exit selection: existing DOM elements in the selection for which no new datum was found. The exit selection is determined by the previous [*selection*.data](#selection_data), and is thus empty until the selection is joined to data. If the exit selection is retrieved more than once after a data join, subsequent calls return the empty selection.
528
529The exit selection is typically used to remove “superfluous” elements corresponding to old data. For example, to update the DIV elements created previously with a new array of numbers:
530
531```js
532div = div.data([1, 2, 4, 8, 16, 32], function(d) { return d; });
533```
534
535Since a key function was specified (as the identity function), and the new data contains the numbers [4, 8, 16] which match existing elements in the document, the update selection contains three DIV elements. Leaving those elements as-is, we can append new elements for [1, 2, 32] using the enter selection:
536
537```js
538div.enter().append("div").text(function(d) { return d; });
539```
540
541Likewise, to remove the exiting elements [15, 23, 42]:
542
543```js
544div.exit().remove();
545```
546
547Now the document body looks like this:
548
549```html
550<div>1</div>
551<div>2</div>
552<div>4</div>
553<div>8</div>
554<div>16</div>
555<div>32</div>
556```
557
558The order of the DOM elements matches the order of the data because the old data’s order and the new data’s order were consistent. If the new data’s order is different, use [*selection*.order](#selection_order) to reorder the elements in the DOM. See the [General Update Pattern](http://bl.ocks.org/mbostock/3808218) example thread for more on data joins.
559
560<a name="selection_datum" href="#selection_datum">#</a> <i>selection</i>.<b>datum</b>([<i>value</i>])
561
562Gets or sets the bound data for each selected element. Unlike [*selection*.data](#selection_data), this method does not compute a join and does not affect indexes or the enter and exit selections.
563
564If a *value* is specified, sets the element’s bound data to the specified value on all selected elements. If the *value* is a constant, all elements are given the same datum; otherwise, if the *value* is a function, then the function is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. The function is then used to set each element’s new data. A null value will delete the bound data.
565
566If a *value* is not specified, returns the bound datum for the first (non-null) element in the selection. This is generally useful only if you know the selection contains exactly one element.
567
568This method is useful for accessing HTML5 [custom data attributes](http://www.w3.org/TR/html5/dom.html#custom-data-attribute). For example, given the following elements:
569
570```html
571<ul id="list">
572 <li data-username="shawnbot">Shawn Allen</li>
573 <li data-username="mbostock">Mike Bostock</li>
574</ul>
575```
576
577You can expose the custom data attributes by setting each element’s data as the built-in [dataset](http://www.w3.org/TR/html5/dom.html#dom-dataset) property:
578
579```js
580selection.datum(function() { return this.dataset; })
581```
582
583### Handling Events
584
585For interaction, selections allow listening for and dispatching of events.
586
587<a name="selection_on" href="#selection_on">#</a> <i>selection</i>.<b>on</b>(<i>typenames</i>[, <i>listener</i>[, <i>capture</i>]])
588
589Adds or removes a *listener* to each selected element for the specified event *typenames*. The *typenames* is a string event type, such as `click`, `mouseover`, or `submit`; any [DOM event type](https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events) supported by your browser may be used. The type may be optionally followed by a period (`.`) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as `click.foo` and `click.bar`. To specify multiple typenames, separate typenames with spaces, such as `input change` or `click.foo click.bar`.
590
591When a specified event is dispatched on a selected node, the specified *listener* will be evaluated for each selected element, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. Listeners always see the latest datum for their element, but the index is a property of the selection and is fixed when the listener is assigned; to update the index, re-assign the listener. To access the current event within a listener, use [d3.event](#event).
592
593If an event listener was previously registered for the same *typename* on a selected element, the old listener is removed before the new listener is added. To remove a listener, pass null as the *listener*. To remove all listeners for a given name, pass null as the *listener* and `.foo` as the *typename*, where `foo` is the name; to remove all listeners with no name, specify `.` as the *typename*.
594
595An optional *capture* flag may be specified which corresponds to the W3C [useCapture flag](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration): “After initiating capture, all events of the specified type will be dispatched to the registered EventListener before being dispatched to any EventTargets beneath them in the tree. Events which are bubbling upward through the tree will not trigger an EventListener designated to use capture.”
596
597If a *listener* is not specified, returns the currently-assigned listener for the specified event *typename* on the first (non-null) selected element, if any. If multiple typenames are specified, the first matching listener is returned.
598
599<a name="selection_dispatch" href="#selection_dispatch">#</a> <i>selection</i>.<b>dispatch</b>(<i>type</i>[, <i>parameters</i>])
600
601Dispatches a [custom event](http://www.w3.org/TR/dom/#interface-customevent) of the specified *type* to each selected element, in order. An optional *parameters* map may be specified to set additional properties of the event. It may contain the following fields:
602
603* [`bubbles`](https://www.w3.org/TR/dom/#dom-event-bubbles) - if true, the event is dispatched to ancestors in reverse tree order.
604* [`cancelable`](https://www.w3.org/TR/dom/#dom-event-cancelable) - if true, *event*.preventDefault is allowed.
605* [`detail`](https://www.w3.org/TR/dom/#dom-customevent-detail) - any custom data associated with the event.
606
607If *parameters* is a function, it is evaluated for each selected element, in order, being passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* as the current DOM element. It must return the parameters map for the current element.
608
609<a name="event" href="#event">#</a> d3.<b>event</b>
610
611The current [event](https://developer.mozilla.org/en-US/docs/DOM/event), if any. This is set during the invocation of an event listener, and is reset after the listener terminates. Use this to access standard event fields such as [*event*.timeStamp](https://www.w3.org/TR/dom/#dom-event-timestamp) and methods such as [*event*.preventDefault](https://www.w3.org/TR/dom/#dom-event-preventdefault). While you can use the native [*event*.pageX](https://developer.mozilla.org/en/DOM/event.pageX) and [*event*.pageY](https://developer.mozilla.org/en/DOM/event.pageY), it is often more convenient to transform the event position to the local coordinate system of the container that received the event using [d3.mouse](#mouse), [d3.touch](#touch) or [d3.touches](#touches).
612
613If you use Babel, Webpack, or another ES6-to-ES5 bundler, be aware that the value of d3.event changes during an event! An import of d3.event must be a [live binding](http://www.2ality.com/2015/07/es6-module-exports.html), so you may need to configure the bundler to import from D3’s ES6 modules rather than from the generated UMD bundle; not all bundlers observe [jsnext:main](https://github.com/rollup/rollup/wiki/jsnext:main). Also beware of conflicts with the [*window*.event](https://developer.mozilla.org/en-US/docs/Web/API/Window/event) global.
614
615<a name="customEvent" href="#customEvent">#</a> d3.<b>customEvent</b>(<i>event</i>, <i>listener</i>[, <i>that</i>[, <i>arguments</i>]])
616
617Invokes the specified *listener*, using the specified *that* `this` context and passing the specified *arguments*, if any. During the invocation, [d3.event](#event) is set to the specified *event*; after the listener returns (or throws an error), d3.event is restored to its previous value. In addition, sets *event*.sourceEvent to the prior value of d3.event, allowing custom events to retain a reference to the originating native event. Returns the value returned by the *listener*.
618
619<a name="mouse" href="#mouse">#</a> d3.<b>mouse</b>(<i>container</i>)
620
621Returns the *x* and *y* coordinates of the [current event](#event) relative to the specified *container*. The container may be an HTML or SVG container element, such as a [G element](http://www.w3.org/TR/SVG/struct.html#Groups) or an [SVG element](http://www.w3.org/TR/SVG/struct.html#SVGElement). The coordinates are returned as a two-element array of numbers [*x*, *y*].
622
623<a name="touch" href="#touch">#</a> d3.<b>touch</b>(<i>container</i>[, <i>touches</i>], <i>identifier</i>)
624
625Returns the *x* and *y* coordinates of the touch with the specified *identifier* associated with the [current event](#event) relative to the specified *container*. The container may be an HTML or SVG container element, such as a [G element](http://www.w3.org/TR/SVG/struct.html#Groups) or an [SVG element](http://www.w3.org/TR/SVG/struct.html#SVGElement). The coordinates are returned as an array of two-element arrays of numbers \[\[*x1*, *y1*], [*x2*, *y2*], …\]. If there is no touch with the specified identifier in *touches*, returns null; this can be useful for ignoring touchmove events where the only some touches have moved. If *touches* is not specified, it defaults to the current event’s [changedTouches](http://developer.apple.com/library/safari/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html#//apple_ref/javascript/instp/TouchEvent/changedTouches) property.
626
627<a name="touches" href="#touches">#</a> d3.<b>touches</b>(<i>container</i>[, <i>touches</i>])
628
629Returns the *x* and *y* coordinates of the touches associated with the [current event](#event) relative to the specified *container*. The container may be an HTML or SVG container element, such as a [G element](http://www.w3.org/TR/SVG/struct.html#Groups) or an [SVG element](http://www.w3.org/TR/SVG/struct.html#SVGElement). The coordinates are returned as an array of two-element arrays of numbers \[\[*x1*, *y1*], [*x2*, *y2*], …\]. If *touches* is not specified, it defaults to the current event’s [touches](http://developer.apple.com/library/safari/documentation/UserExperience/Reference/TouchEventClassReference/TouchEvent/TouchEvent.html#//apple_ref/javascript/instp/TouchEvent/touches) property.
630
631### Control Flow
632
633For advanced usage, selections provide methods for custom control flow.
634
635<a name="selection_each" href="#selection_each">#</a> <i>selection</i>.<b>each</b>(<i>function</i>)
636
637Invokes the specified *function* for each selected element, passing in passed the current datum (*d*), the current index (*i*), and the current group (*nodes*), with *this* of the current DOM element. This method can be used to invoke arbitrary code for each selected element, and is useful for creating a context to access parent and child data simultaneously, such as:
638
639```js
640parent.each(function(p, j) {
641 d3.select(this)
642 .selectAll(".child")
643 .text(function(d, i) { return "child " + d.name + " of " + p.name; });
644});
645```
646
647See [Sized Donut Multiples](http://bl.ocks.org/mbostock/4c5fad723c87d2fd8273) for an example.
648
649<a name="selection_call" href="#selection_call">#</a> <i>selection</i>.<b>call</b>(<i>function</i>[, <i>arguments…</i>])
650
651Invokes the specified *function* exactly once, passing in this selection along with any optional *arguments*. Returns this selection. This is equivalent to invoking the function by hand but facilitates method chaining. For example, to set several styles in a reusable function:
652
653```javascript
654function name(selection, first, last) {
655 selection
656 .attr("first-name", first)
657 .attr("last-name", last);
658}
659```
660
661Now say:
662
663```javascript
664d3.selectAll("div").call(name, "John", "Snow");
665```
666
667This is equivalent to:
668
669```javascript
670name(d3.selectAll("div"), "John", "Snow");
671```
672
673<a name="selection_empty" href="#selection_empty">#</a> <i>selection</i>.<b>empty</b>()
674
675Returns true if this selection contains no (non-null) elements.
676
677<a name="selection_nodes" href="#selection_nodes">#</a> <i>selection</i>.<b>nodes</b>()
678
679Returns an array of all (non-null) elements in this selection.
680
681<a name="selection_node" href="#selection_node">#</a> <i>selection</i>.<b>node</b>()
682
683Returns the first (non-null) element in this selection. If the selection is empty, returns null.
684
685<a name="selection_size" href="#selection_size">#</a> <i>selection</i>.<b>size</b>()
686
687Returns the total number of elements in this selection.
688
689### Local Variables
690
691D3 locals allow you to define local state independent of data. For instance, when rendering [small multiples](http://bl.ocks.org/mbostock/e1192fe405703d8321a5187350910e08) of time-series data, you might want the same *x*-scale for all charts but distinct *y*-scales to compare the relative performance of each metric. D3 locals are scoped by DOM elements: on set, the value is stored on the given element; on get, the value is retrieved from given element or the nearest ancestor that defines it.
692
693<a name="local" href="#local">#</a> d3.<b>local</b>()
694
695Declares a new local variable. For example:
696
697```js
698var foo = d3.local();
699```
700
701Like `var`, each local is a distinct symbolic reference; unlike `var`, the value of each local is also scoped by the DOM.
702
703<a name="local_set" href="#local_set">#</a> <i>local</i>.<b>set</b>(<i>node</i>, <i>value</i>)
704
705Sets the value of this local on the specified *node* to the *value*, and returns the specified *value*. This is often performed using [*selection*.each](#selection_each):
706
707```js
708selection.each(function(d) { foo.set(this, d.value); });
709```
710
711If you are just setting a single variable, consider using [*selection*.property](#selection_property):
712
713```js
714selection.property(foo, function(d) { return d.value; });
715```
716
717<a name="local_get" href="#local_get">#</a> <i>local</i>.<b>get</b>(<i>node</i>)
718
719Returns the value of this local on the specified *node*. If the *node* does not define this local, returns the value from the nearest ancestor that defines it. Returns undefined if no ancestor defines this local.
720
721<a name="local_remove" href="#local_remove">#</a> <i>local</i>.<b>remove</b>(<i>node</i>)
722
723Deletes this local’s value from the specified *node* and returns its previous value. Returns true if the *node* defined this local prior to removal, and false otherwise. If ancestors also define this local, those definitions are unaffected, and thus [*local*.get](#local_get) will still return the inherited value.
724
725<a name="local_toString" href="#local_toString">#</a> <i>local</i>.<b>toString</b>()
726
727Returns the automatically-generated identifier for this local. This is the name of the property that is used to store the local’s value on elements, and thus you can also set or get the local’s value using *element*[*local*] or by using [*selection*.property](#selection_property).
728
729### Namespaces
730
731XML namespaces are fun! Right? Fortunately you can mostly ignore them.
732
733<a name="namespace" href="#namespace">#</a> d3.<b>namespace</b>(<i>name</i>)
734
735Qualifies the specified *name*, which may or may not have a namespace prefix. If the name contains a colon (`:`), the substring before the colon is interpreted as the namespace prefix, which must be registered in [d3.namespaces](#namespaces). Returns an object `space` and `local` attributes describing the full namespace URL and the local name. For example:
736
737```js
738d3.namespace("svg:text"); // {space: "http://www.w3.org/2000/svg", local: "text"}
739```
740
741If the name does not contain a colon, this function merely returns the input name.
742
743<a name="namespaces" href="#namespaces">#</a> d3.<b>namespaces</b>
744
745The map of registered namespace prefixes. The initial value is:
746
747```js
748{
749 svg: "http://www.w3.org/2000/svg",
750 xhtml: "http://www.w3.org/1999/xhtml",
751 xlink: "http://www.w3.org/1999/xlink",
752 xml: "http://www.w3.org/XML/1998/namespace",
753 xmlns: "http://www.w3.org/2000/xmlns/"
754}
755```
756
757Additional prefixes may be assigned as needed to create elements or attributes in other namespaces.