D3.js Basics

By Xah Lee. Date: . Last updated: .

d3 learning notes.

can select things.


d3.selectAll("p").style("color", "white");

Yet, you can still manipulate individual nodes as needed:


d3.select("body").style("background-color", "black");

can also style things.

note that style is a method of whatever those select returns.

so, this means, those select must return some d3 object.

d3.selectAll("p").style("color", "pinnk");
d3.select("body").style("background-color", "black");
// For example, to randomly color paragraphs:
d3.selectAll("p").style("color", function() {
  return "hsl(" + Math.random() * 360 + ",100%,50%)";
// To alternate shades of gray for even and odd nodes:
d3.selectAll("p").style("color", function(d, i) {
  return i % 2 ? "#fff" : "#eee";
    .style("font-size", function(x) { return x + "px"; });

binding data

one big thing about d3 is binding data to elements.

d3 is designed with the idea of data in, and visual stuff out.

binding data to element basically means, set data as a property of a object (a DOM element object). [see JS: Property Overview]

typically done like this


d3 enter

very strange thing.


The data is stored as property to element as __data__

d3 select or selectAll. can be nested, e.g.


that means, its properly implemented as a obect, the d3 object, and there is a property “selection”, e.g. d3.selection, whose value is dom. Initially, the default value is document (or null). When a selection method is called, it checks if it's null, if so, target it as document. Else, use its value d3.selection as selection target.

Check if the above is true.

.data() returns a a object that represents “update selection”


it also has enter and exit methods.


find out if d3.select, when no result, does it actually auto create them. Seems so.