* checkpoint vitepress docs * edits * edits * hero drop shadow * d3-array edits * resolve d3 * split d3-array * move d3-array stuff around * d3-array is collapsed: true * italicize parameter names * searching edits * update dependencies * d3-array edits * array edits * array edits * array edits * array edits * array edits * move files * array edits * array edits * array edits * getting started edits * modules page * array edits * more structure * live example * dsv edits * fetch edits * dsv edits * random edits * time format edits * time edits * time edits * modules edits * color edits * color edits * interpolate edits * scale-chromatic edits * selection edits * break up d3-interpolate * scale edits * time scale edits * scale edits * scale edits * band edits * band edits * more descriptive titles * band and point edits * sequential edits * diverging edits * quantize edits * quantile edits * threshold edits * doc edits * fix titles * sequential edits * axis edits * axis edits * axis edits * shape edits * shape edits * dark mode chart * dark mode chart * curve edits * interpolate edits * line edits * link edits * radial edits * pie edits * symbol edits * stack edits * stack examples * path edits * polygon edits * quadtree edits * random examples * ease edits * ease edits * ease edits * timer edits * delaunay edits * quadtree find example * voronoi edits * dispatch edits * contour edits * chord edits * chord edits * fix find highlight * quadtree animation * transition edits * transition edits * transition edits * zoom edits * drag edits * brush edits * force edits * voronoi neighbors example * hierarchy edits * api edits * community edits * getting started edits * geo edits * Add short "D3 in React" section (#3659) * Add short "D3 in React" section I know you removed the TODO but I was already trying to fill it in! I think just making the distinction of modules that touch the DOM and those that don't was super clarifying for me personally when I figured that out. And I always forget the most basic ref pattern (and still might've messed it up here). I don't think we should get into updating or interactivity or whatever, but I think just this much goes a long way toward demystifying (and showing just the most basic best practices). * forgot i made data generic, rm reference to normal distribution * useEffect cleans up after itself Co-authored-by: Mike Bostock <mbostock@gmail.com> * Update getting-started.md --------- Co-authored-by: Mike Bostock <mbostock@gmail.com> * build fixes * index edits --------- Co-authored-by: Toph Tucker <tophtucker@gmail.com>
13 KiB
Selecting elements
A selection is a set of elements from the DOM. Typically these elements are identified by selectors such as .fancy for 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. There is also selection.selectChild and selection.selectChildren for direct children.
By convention, selection methods that return the current selection such as selection.attr 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);
selection()
Source · Selects the root element, document.documentElement.
const root = d3.selection();
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);
select(selector)
Source · Selects the first element that matches the specified selector string.
const svg = d3.select("#chart");
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:
const 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 document.body.
d3.select(document.body).style("background", "red");
Or, to make a clicked paragraph red:
d3.selectAll("p").on("click", (event) => d3.select(event.currentTarget).style("color", "red"));
selectAll(selector)
Source · Selects all elements that match the specified selector string.
const p = d3.selectAll("p");
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.
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 an iterable, or a pseudo-array such as a NodeList. For example, to color all links red:
d3.selectAll(document.links).style("color", "red");
selection.select(selector)
Source · For each selected element, selects the first descendant element that matches the specified selector string.
const b = d3.selectAll("p").select("b"); // the first <b> in every <p>
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.
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:
const 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.
:::warning CAUTION selection.select propagates the parent’s data to the selected child. :::
selection.selectAll(selector)
Source · For each selected element, selects the descendant elements that match the specified selector string.
const b = d3.selectAll("p").selectAll("b"); // every <b> in every <p>
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 to propagate data to children.
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 an iterable, 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:
const 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.
selection.filter(filter)
Source · Filters the selection, returning a new selection that contains only the elements for which the specified filter is true. For example, to filter a selection of table rows to contain only even rows:
const even = d3.selectAll("tr").filter(":nth-child(even)");
This is approximately equivalent to using d3.selectAll directly, although the indexes may be different:
const even = d3.selectAll("tr:nth-child(even)");
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]). Using a function:
const even = d3.selectAll("tr").filter((d, i) => i & 1);
Or using selection.select (and avoiding an arrow function, since this is needed to refer to the current element):
const 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.
selection.selectChild(selector)
Source · Returns a new selection with the (first) child of each element of the current selection matching the selector.
d3.selectAll("p").selectChild("b") // the first <b> child of every <p>
If no selector is specified, selects the first child (if any). If the selector is specified as a string, selects the first child that matches (if any). If the selector is a function, it is evaluated for each of the children nodes, in order, being passed the child (child), the child’s index (i), and the list of children (children); the method selects the first child for which the selector return truthy, if any.
:::warning CAUTION selection.selectChild propagates the parent’s data to the selected child. :::
selection.selectChildren(selector)
Source · Returns a new selection with the children of each element of the current selection matching the selector. If no selector is specified, selects all the children. If the selector is specified as a string, selects the children that match (if any). If the selector is a function, it is evaluated for each of the children nodes, in order, being passed the child (child), the child’s index (i), and the list of children (children); the method selects all children for which the selector return truthy.
selection.selection()
Source · Returns the selection (for symmetry with transition.selection).
matcher(selector)
Source · 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:
const div = selection.filter("div");
Is equivalent to:
const 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.)
selector(selector)
Source · 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:
const div = selection.select("div");
Is equivalent to:
const div = selection.select(d3.selector("div"));
selectorAll(selector)
Source · 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:
const div = selection.selectAll("div");
Is equivalent to:
const div = selection.selectAll(d3.selectorAll("div"));
window(node)
Source · 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.
style(node, name)
Source · 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.