D3.js offers an interesting, declarative way for creating data-driven documents in JavaScript. Core of such approach are selections.
Selection is a way of picking existing (or "soon to exist") elements in DOM that forms a grouping.
To start on root level use d3.select
; to select (further) on already existing selection use selection.select
etc.
There are two ways of selecting things in D3.js API:
-
select
- will select first (or the only) matching element (in document order) from selection it operates on;
example:d3.selectAll('h2').select('div')
will select every 1stdiv
descendant in everyh2
element in document;
since select chooses only first element, it will flatten the hierarchy and pass the associated data down to the selected children nodes
TODO: Visualize -
selectAll
- will select all matching descendant element (in document order) from selection it operates on;
example:d3.selectAll('h2').selectAll('div')
will select alldiv
descendant in everyh2
element in document;
selectAll preserves previous grouping and creates selection hierarchy (often described as 'nested selection'), therefore data is not passed down to children nodes;
we can however assign data to such selection using enter, update and exit selections (operators?) and tell D3.js how to react to data changes (ie. add, update or remove elements, that visualize data in document)
TODO: Visualize
TODO: enter, update and exit with data
, enter
and exit
TODO: key function as a second param to data(values, keyFunc)
- Mike Bostock, How Selections Work
- Mike Bostock, Nested Selections
- Mike Bostock, Thinking with Joins