Selections allow powerful data-driven transformation of the document object model (DOM): set attributes, styles, properties, HTML or text content, and more. Using the data join’s enter and exit selections, you can also add or remove elements to correspond to data.
Selection 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:
d3.selectAll("p")
.attr("class", "graf")
.style("color", "red");
This is equivalent to:
var p = d3.selectAll("p");
p.attr("class", "graf");
p.style("color", "red");
By 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:
d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500)
.append("g")
.attr("transform", "translate(20,20)")
.append("rect")
.attr("width", 920)
.attr("height", 460);
Selections 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!
If you use NPM, npm install d3-selection
. Otherwise, download the latest release. You can also load directly from d3js.org, either as a standalone library or as part of D3 4.0. AMD, CommonJS, and vanilla environments are supported. In vanilla, a d3
global is exported:
<script src="https://d3js.org/d3-selection.v1.min.js"></script>
<script>
var div = d3.selectAll("div");
</script>
Try d3-selection in your browser.
- Selecting Elements
- Modifying Elements
- Joining Data
- Handling Events
- Control Flow
- Local Variables
- Namespaces
Selection methods accept W3C selector strings 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 and d3.selectAll, query the entire document; the subselection methods, selection.select and selection.selectAll, restrict selection to descendants of the selected elements.
Selects 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:
d3.selection.prototype.checked = function(value) {
return arguments.length < 1
? this.property("checked")
: this.property("checked", !!value);
};
And then to use:
d3.selectAll("input[type=checkbox]").checked(true);
Selects 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:
var anchor = d3.select("a");
If 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:
d3.selectAll("p").on("click", function() {
d3.select(this).style("color", "red");
});
Selects 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:
var paragraph = d3.selectAll("p");
If 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:
d3.selectAll(document.links).style("color", "red");
# selection.select(selector) <>
For 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:
var b = d3.selectAll("p").select("b");
If 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 (nodes[i]). It must return an element, or null if there is no matching element. For example, to select the previous sibling of each paragraph:
var previous = d3.selectAll("p").select(function() {
return this.previousElementSibling;
});
Unlike 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. See Nested Selections and How Selections Work for more on this topic.
# selection.selectAll(selector) <>
For 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 9E88 , 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 to propagate data to children. For example, to select the bold elements in every paragraph:
var b = d3.selectAll("p").selectAll("b");
If 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 (nodes[i]). 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:
var sibling = d3.selectAll("p").selectAll(function() {
return [
this.previousElementSibling,
this.nextElementSibling
];
});
Unlike 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. See Nested Selections and How Selections Work for more on this topic.
Filters 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 the filter 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 (nodes[i]).
For example, to filter a selection of table rows to contain only even rows:
var even = d3.selectAll("tr").filter(":nth-child(even)");
This is approximately equivalent to using d3.selectAll directly, although the indexes may be different:
var even = d3.selectAll("tr:nth-child(even)");
Similarly, using a function:
var even = d3.selectAll("tr").filter(function(d, i) { return i & 1; });
Or using selection.select:
var even = d3.selectAll("tr").select(function(d, i) { return i & 1 ? this : null; });
Note 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 preceding sibling elements in the DOM.
The returned filtered selection preserves the parents of this selection, but like array.filter, it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed.
Returns 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.)
This method is commonly used to merge the enter and update selections after a data-join. After modifying the entering and updating elements separately, you can merge the two selections and perform operations on both without duplicate code. For example:
var circle = svg.selectAll("circle").data(data) // UPDATE
.style("fill", "blue");
circle.exit().remove(); // EXIT
circle = circle.enter().append("circle") // ENTER
.style("fill", "green")
.merge(circle) // ENTER + UPDATE
.style("stroke", "black");
See selection.data for a more complete explanation of this code, which is known as the general update pattern.
This 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.
Given the specified selector, returns a function which returns true if this
element matches the specified selector. This method is used internally by selection.filter. For example, this:
var div = selection.filter("div");
Is equivalent to:
var div = selection.filter(d3.matcher("div"));
(Although D3 is not a compatibility layer, this implementation does support vendor-prefixed implementations due to the recent standardization of element.matches.)
Given 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. For example, this:
var div = selection.select("div");
Is equivalent to:
var div = selection.select(d3.selector("div"));
Given 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. For example, this:
var div = selection.selectAll("div");
Is equivalent to:
var div = selection.selectAll(d3.selectorAll("div"));
Returns 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.
Returns the value of the style property with the specified name for the specified node. If the node has an inline style with the specified name, its value is returned; otherwise, the computed property value is returned. See also selection.style.
After 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:
d3.select("a")
.attr("name", "fred")
.style("color", "red");
To experiment with selections, visit 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.
# selection.attr(name[, value]) <>
If 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, 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 (nodes[i]). The function’s return value is then used to set each element’s attribute. A null value will remove the specified attribute.
If 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.
The specified name may have a namespace prefix, such as xlink:href
to specify the href
attribute in the XLink namespace. See namespaces for the map of supported namespaces; additional namespaces can be registered by adding to the map.
# selection.classed(names[, value]) <>
If 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:
selection.classed("foo bar", true);
If the value is truthy, then all elements are assigned the specified classes; otherwise, the classes are unassigned. If the value 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 (nodes[i]). 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:
selection.classed("foo", function() { return Math.random() > 0.5; });
If 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.
# selection.style(name[, value[, priority]]) <>
If 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, 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 (nodes[i]). 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).
If a value is not specified, returns the current value of the specified style property for the first (non-null) element in the selection. The current value is defined as the element’s inline value, if present, and otherwise its computed value. Accessing the current style value is generally useful only if you know the selection contains exactly one element.
Caution: 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!
# selection.property(name[, value]) <>
Some 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.
If 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, 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 (nodes[i]). The function’s return value is then used to set each element’s property. A null value will delete the specified property.
If 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.
If a value is specified, sets the text content 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, 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 (nodes[i]). The function’s return value is then used to set each element’s text content. A null value will clear the content.
If 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.
If a value is specified, sets the inner HTML 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, 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 (nodes[i]). The function’s return value is then used to set each element’s inner HTML. A null value will clear the content.
If 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.
Use selection.append or 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 to convert a DOM subtree to text. See also the innersvg polyfill, which provides a shim to support the innerHTML property on SVG elements.
If the specified type is a string, appends a new element of this type (tag name) as the last child of each selected element, or before the next following sibling in the update selection if this is an enter selection. The latter behavior for enter selections allows you to insert elements into the DOM in an order consistent with the new bound data; however, note that selection.order may still be required if updating elements change order (i.e., if the order of new data is inconsistent with old data).
If the specified type 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 (nodes[i]). 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:
d3.selectAll("p").append("div");
This is equivalent to:
d3.selectAll("p").append(function() {
return document.createElement("div");
});
Which is equivalent to:
d3.selectAll("p").select(function() {
return this.appendChild(document.createElement("div"));
});
In 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.
The specified name may have a namespace prefix, such as svg:text
to specify a text
attribute in the SVG namespace. See 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
).
# selection.insert(type[, before]) <>
If the specified type is a string, inserts a new element of this type (tag name) before the first element matching the specified before selector for each selected element. For example, a before selector :first-child
will prepend nodes before the first child. If before is not specified, it defaults to null. (To append elements in an order consistent with bound data, use selection.append.)
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 (nodes[i]). 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 append a DIV element to each paragraph:
d3.selectAll("p").insert("div");
This is equivalent to:
d3.selectAll("p").insert(function() {
return document.createElement("div");
});
Which is equivalent to:
< F438 div class="highlight highlight-source-js notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="d3.selectAll("p").select(function() { return this.insertBefore(document.createElement("div"), null); });">d3.selectAll("p").select(function() { return this.insertBefore(document.createElement("div"), null); });