Skip to content
mbostock edited this page May 28, 2011 · 84 revisions

Selections

A selection is a filtered set of elements from the current document. After selecting elements, you can apply operators to them, such as setting attributes or styles. You can also join selections to data; this data is available to operators for data-driven transformations. In addition, joining to data produces enter and exit subselections, letting you add or remove elements in response to changes in data.

D3 uses CSS3 Selectors to filter elements. For example, you can select elements by tag ("tag"), class (".class"), unique identifier ("#id"), attribute ("[name=value]"), or containment ("parent child"). Selectors can also be intersected (".a.b") or unioned (".a, .b").

Any number of operators can be applied to selected elements. These operators wrap the W3C DOM API, setting attributes (attr), styles (style), properties (property), HTML (html) and text (text) content. Operator values are specified either as constants or functions; the latter are evaluated for each element. While the built-in operators satisfy most needs, the each operator invokes an arbitrary JavaScript callback for total generality. Since each selection is simply an array, elements can also be accessed directly (e.g., [0]).

D3 supports method chaining for brevity when applying multiple operators: the operator return value is the selection. The append and insert operators add a new element for each element in the current selection, returning the added nodes, thus allowing the convenient creation of nested structures. The remove operator discards selected elements.

Generating Selections

d3.select(selector)
d3.select(node)

d3.selectAll(selector)
d3.selectAll(nodes)

Working with Selections

Whereas the top-level select methods query the entire document, a selection’s select and selectAll operators restrict queries to descendants of each selected element; we call this subselection. For example, d3.selectAll("p").select("b") returns the first bold (“b”) elements in every paragraph (“p”) element.

selection.select(selector)

selection.selectAll(selector)

Subselecting via selectAll groups elements by ancestor. Thus, d3.selectAll("p").selectAll("b") groups by paragraph, while d3.selectAll("p b") returns a flat selection. Subselect- ing via select is similar, but preserves groups and propagates data. Grouping plays an important role in the data join, and functional operators may depend on the numeric index of the current element within its group.

Clone this wiki locally