new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

D3 · all subjects

d3-selection

85 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

d3-selection module overview

The d3-selection module is used to transform the DOM by selecting elements and joining to data.

d3-selection topics and documentation structure

The d3-selection module has six main documentation areas: selecting elements (querying for DOM elements), modifying elements (modifying attributes of selected elements), joining data (joining data to selected elements for visualization), handling events (declaring event listeners for interaction), control flow (iterating over selected elements), local variables (attaching state to elements), and namespaces (dealing with XML namespaces).

d3-selection module purpose

The d3-selection module enables powerful data-driven transformation of the DOM. It allows setting attributes, styles, properties, HTML or text content on selected elements. Using the data join's enter and exit selections, you can add or remove elements to correspond to data.

selection.call() invokes function once with selection and optional arguments

selection.call(function, ...arguments) invokes the specified function exactly once, passing in the selection along with any optional arguments. Always returns the selection, not the return value of the called function. This facilitates method chaining.

selection.call() example with attribute setter

function name(selection, first, last) { selection .attr("first-name", first) .attr("last-name", last); } d3.selectAll("div").call(name, "John", "Snow");

selection.empty() returns true if selection contains no elements

selection.empty() returns true if the selection contains no (non-null) elements.

selection.empty() example

d3.selectAll("p").empty() // false, here

selection.nodes() returns array of all elements

selection.nodes() returns an array of all (non-null) elements in the selection. This is equivalent to Array.from(selection).

selection.nodes() example

d3.selectAll("p").nodes() // [p, p, p, …]

selection[Symbol.iterator]() returns iterator over selected elements

selection[Symbol.iterator]() returns an iterator over the selected (non-null) elements, allowing the selection to be iterable in for...of loops and with the spread operator.

selection[Symbol.iterator]() example with for loop

for (const element of selection) { console.log(element); }

selection[Symbol.iterator]() example flattening with spread operator

const elements = [...selection];

selection.node() returns first element

selection.node() returns the first (non-null) element in the selection. If the selection is empty, returns null.

selection.size() returns total count of elements

selection.size() returns the total number of (non-null) elements in the selection.

selection.each() invokes function for each selected element

selection.each(function) invokes the specified function for each selected element in order. The function receives the current datum (d), the current index (i), and the current group (nodes) as parameters, with this as the current DOM element (nodes[i]). This method enables arbitrary code execution for each selected element and is useful for accessing parent and child data simultaneously.

selection.each() example with child access

parent.each(function(p, j) { d3.select(this) .selectAll(".child") .text(d => `child ${d.name} of ${p.name}`); });

selection.dispatch() signature and usage

selection.dispatch(type, parameters) dispatches a custom event of the specified type to each selected element, in order. Example: d3.select("p").dispatch("click").

selection.on() signature and usage

selection.on(typenames, listener, options) adds or removes a listener to each selected element for specified event typenames. Example: d3.selectAll("p").on("click", (event) => console.log(event)). The typenames is a string event type such as click, mouseover, or submit, or any DOM event type supported by the browser. The type may optionally be followed by a period (.) and a name to register multiple callbacks for the same event type, such as click.foo and click.bar. Multiple typenames are separated by spaces, such as 'input change' or 'click.foo click.bar'.

selection.on() listener context and parameters

When a specified event is dispatched on a selected element, the listener is evaluated with the current event (event) and current datum (d) as parameters, and this is bound to the current DOM element (event.currentTarget). Listeners always see the latest datum for their element.

selection.on() listener removal

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. To remove all listeners with no name, specify . as the typename. If 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.

selection.on() options parameter

An optional options object may specify characteristics about the event listener, such as whether it is capturing or passive; these options are passed to element.addEventListener.

selection.dispatch() parameters object fields

An optional parameters object may be specified with the following fields: bubbles (boolean, if true the event is dispatched to ancestors in reverse tree order), cancelable (boolean, if true event.preventDefault is allowed), detail (any custom data associated with the event).

selection.dispatch() parameters as function

If parameters is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this bound to the current DOM element (nodes[i]). It must return the parameters for the current element.

d3.pointer() event types

d3.pointer() accepts event as a MouseEvent, PointerEvent, Touch, or custom event holding a UIEvent as event.sourceEvent.

d3.pointer() target parameter and coordinate transformation

If target is not specified, d3.pointer() defaults to the source event's currentTarget property, if available. If the target is an SVG element, coordinates are transformed using the inverse of the screen coordinate transformation matrix. If the target is an HTML element, coordinates are translated relative to the top-left corner of the target's bounding client rectangle. Otherwise, [event.pageX, event.pageY] is returned.

d3.pointers() signature and usage

d3.pointers(event, target) returns an array [[x0, y0], [x1, y1]…] of coordinates of the specified event's pointer locations relative to the specified target. Example: const points = d3.pointers(event).

d3.pointers() behavior with touch and other events

For touch events, d3.pointers() returns an array of positions corresponding to the event.touches array. For other events, it returns a single-element array.

d3.pointers() target parameter default

If target is not specified in d3.pointers(), it defaults to the source event's currentTarget property, if any.

d3.local() declaration

d3.local() declares a new local variable. Like var, each local is a distinct symbolic reference; unlike var, the value of each local is scoped by the DOM.

local.set(node, value) signature and behavior

local.set(node, value) sets the value of a local on the specified node and returns the specified value. The value is stored on the given element.

local.set() with selection.each()

Example of setting a local value: selection.each(function(d) { foo.set(this, d.value); })

local.set() with selection.property()

For setting a single variable, local values can be set using selection.property(foo, (d) => d.value) as an alternative to using local.set().

local.get(node) signature and behavior

local.get(node) returns the value of a local on the specified node. If the node does not define this local, it returns the value from the nearest ancestor that defines it. Returns undefined if no ancestor defines this local.

local.get() with selection.each()

Example of getting a local value: selection.each(function() { const value = foo.get(this); })

local.remove(node) signature and behavior

local.remove(node) deletes a local's value from the specified node and returns true if the node defined this local prior to removal, false otherwise. If ancestors also define this local, those definitions are unaffected, and local.get() will still return the inherited value.

local.remove() with selection.each()

Example of removing a local value: selection.each(function() { foo.remove(this); })

local.toString() signature and behavior

local.toString() returns the automatically-generated identifier for a local. This is the name of the property used to store the local's value on elements, so you can also set or get the local's value using element[local] or by using selection.property().

D3 locals use case: small multiples with independent scales

D3 locals are useful for rendering small multiples of time-series data where you want the same x scale for all charts but distinct y scales to compare the relative performance of each metric.

D3 locals scoping by DOM elements

D3 locals are scoped by DOM elements: on set, the value is stored on the given element; on get, the value is retrieved from the given element or the nearest ancestor that defines it.

Locals rarely used in practice

Locals are rarely used in D3. It may be easier to store state in the selection's data instead.

selection.sort signature and behavior

selection.sort(compare) returns a new selection containing a copy of each group in the selection sorted according to the compare function. After sorting, re-inserts elements to match the resulting order per selection.order. The compare function, which defaults to ascending, is passed two elements' data a and b to compare and should return a negative, positive, or zero value. If negative, a should be before b; if positive, a should be after b; otherwise they are equal and the order is arbitrary.

selection.remove behavior

selection.remove() removes the selected elements from the document and returns this selection containing 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 or selection.insert to re-add elements.

selection.attr signature and behavior

selection.attr(name, value) sets the attribute with the specified name to the specified value on the selected elements and returns the selection. If value is a constant, all elements get the same attribute value. If value is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i]. The function's return value sets each element's attribute. A null value removes the attribute. If value is not specified, returns the current value of the attribute for the first non-null element in the selection. The name may have a namespace prefix like xlink:href.

selection.classed signature and behavior

selection.classed(names, value) assigns or unassigns CSS class names on selected elements by setting the class attribute or modifying the classList property, and returns the selection. The names parameter is a string of space-separated class names (e.g., 'foo bar' to assign classes foo and bar). If value is truthy, classes are assigned; otherwise they are unassigned. If value is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i]. The function's return value determines whether to assign or unassign classes. If value is not specified, returns true if and only if the first non-null selected element has the specified classes.

selection.style signature and behavior

selection.style(name, value, priority) sets the style property with the specified name to the specified value on selected elements and returns the selection. If value is a constant, all elements get the same style property value. If value is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i]. The function's return value sets each element's style property. A null value removes the style property. An optional priority may be specified as null or the string 'important' (without the exclamation point). If value is not specified, returns the current value of the style property for the first non-null element. The current value is defined as the element's inline value if present, otherwise its computed value. CSS styles typically have associated units, for example '3px' is valid for stroke-width but '3' is not; some browsers implicitly assign px but not all do.

selection.property signature and behavior

selection.property(name, value) gets or sets properties on HTML elements that are not addressable using attributes or styles, such as a form field's text value and a checkbox's checked boolean. If value is specified, it sets the property with the specified name. If value is a constant, all elements get the same property value. If value is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i]. The function's return value sets each element's property. A null value deletes the property. If value is not specified, returns the value of the property for the first non-null element in the selection.

selection.text signature and behavior

selection.text(value) sets the text content to the specified value on all selected elements, replacing any existing child elements, and returns the selection. If value is a constant, all elements get the same text content. If value is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i]. The function's return value sets each element's text content. A null value clears the content. If value is not specified, returns the text content for the first non-null element in the selection.

selection.html signature and behavior

selection.html(value) sets the inner HTML to the specified value on all selected elements, replacing any existing child elements, and returns the selection. If value is a constant, all elements get the same inner HTML. If value is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i]. The function's return value sets each element's inner HTML. A null value clears the content. If value is not specified, returns the inner HTML for the first non-null element in the selection. selection.html is only supported on HTML elements; SVG elements and other non-HTML elements do not support the innerHTML property.

selection.append signature and behavior

selection.append(type) appends a new element of the specified type (tag name) as the last child of each selected element. If type is a string, a new element with that tag name is created. If type is a function, it is evaluated for each selected element in order, being passed the current datum (d), current index (i), and current group (nodes), with this as the current DOM element nodes[i], and should return an element to be appended. This method returns a new selection containing the appended elements. Each new element inherits the data of the current elements in the same manner as selection.select. The type may have a namespace prefix such as svg:text; if no namespace is specified, it is inherited from the parent element or, if the name is a known prefix, the corresponding namespace is used (e.g., svg implies svg:svg).

selection.insert signature and behavior

selection.insert(type, before) inserts a new element of the specified type (tag name) before the first element matching the specified before selector for each selected element. For example, before = ':first-child' prepends nodes before the first child. If before is not specified, it defaults to null. Both type and before may be functions which are evaluated for each selected element in order, being passed the current datum (d), current index (i), and 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. This method returns a new selection containing the inserted elements. Each new element inherits the data of the current elements in the same manner as selection.select. The type may have a namespace prefix such as svg:text; if no namespace is specified, it is inherited from the parent element or the corresponding namespace is used for known prefixes.

selection.clone signature and behavior

selection.clone(deep) inserts clones of the selected elements immediately following the selected elements and returns a selection of the newly added clones. If deep is truthy, the descendant nodes of the selected elements are cloned as well. Otherwise, only the elements themselves are cloned.

selection.order behavior

selection.order() re-inserts elements into the document such that the document order of each group matches the selection order. This is equivalent to calling selection.sort if the data is already sorted, but much faster.

selection.raise behavior

selection.raise() re-inserts each selected element, in order, as the last child of its parent. This is equivalent to calling selection.each(function() { this.parentNode.appendChild(this); }).

selection.lower behavior

selection.lower() re-inserts each selected element, in order, as the first child of its parent. This is equivalent to calling selection.each(function() { this.parentNode.insertBefore(this, this.parentNode.firstChild); }).

d3.create signature and behavior

d3.create(name) returns a single-element selection containing a detached element of the given name in the current document. This method assumes the HTML namespace, so you must specify a namespace explicitly when creating SVG or other non-HTML elements. For example, d3.create('svg') is equivalent to svg:svg, and d3.create('svg:g') creates an SVG G element. d3.create('g') creates an HTML G (unknown) element.

d3.creator signature and behavior

d3.creator(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 and selection.insert to create new elements. For example, selection.append('div') is equivalent to selection.append(d3.creator('div')). It supports namespace prefixes such as for SVG elements.

Selection mutability and method chaining

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, elements are necessarily mutable as selections drive transformations of the document. Selection methods typically return the current selection or a new selection, allowing the concise application of multiple operations via method chaining.

Pitfall: :nth-child is one-based, selection index is zero-based

The :nth-child pseudo-class uses a one-based index, while D3 selection indexes are zero-based. This difference means filter functions based on selection index do not have precisely the same meaning as :nth-child pseudo-class selectors.

Data propagation in selection.select vs selection.selectAll

selection.select() propagates the parent's data to the selected child and preserves the existing group structure. In contrast, selection.selectAll() does not inherit data from the parent selection; use selection.data() to propagate data to children.

d3.selectAll() selects all matching elements in document order

d3.selectAll(selector) selects all elements that match the specified selector string in document order (top-to-bottom). If no elements match or the selector is null or undefined, returns an empty selection. If the selector is not a string, it selects the specified array of nodes, iterable, or pseudo-array such as NodeList instead.

Give your agent this brain