Like other JS libraries, D3 builds on the concept of selection (i.e. a filtered set of elements queried from the current document). Selection is at the core of D3 and it basically involves two steps: 1) identify a set of elements using simple predicates and 2) apply a series of operators that modify those elements. See, for example, Bostock (2011):
D3’s basic elements
- operators act on selections, modifying content.
- Data joins enable functional operators that depend on data by binding input data to elements. They also produce enter and exit subselections, which create and destroy elements so that these correspond with the data.
- Animated transitions interpolate attributes and styles over time
- event handlers: special operators which respond to user input and enable interaction
- helper modules: layouts and scales which simplify common visualization tasks
D3 adopts the W3C Selectors API, which is a mini-language that consists of predicates that filter elements, for example, by tag (“tag”), class (“.class”), unique identifiers (“#id”), attribute (“[name=value]”). The intersection of predicates can be selected (“.a.b”) or several can be selected (“.a, .b”).
‘select‘ and ‘selectAll‘ methods can be used to obtain selections. While ‘select’ selects only the first element that matches the predicate, ‘selectAll’ selects all matching elements.
Selections can be specified via subselection, which restricts queries to descendants of each selected element. For example, d3.selectAll(“p”).select(“b”) returns the first bold (“b”) elements in every paragraph (“p”) element.
Can be applied to ‘attr’, ‘style’, ‘property’, ‘html’ and ‘text’ content. They are either specified as constants or functions.
The ‘append‘ and ‘insert‘ operators add a new element for each element in the current selection. The ‘remove’ operator discards selected elements.
An example of D3’s syntax and structure by Bostock (2011):