O'Reilly logo

Interactive Data Visualization for the Web, 2nd Edition by Scott Murray

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix E. Quick Reference

Here is a list of the most commonly used D3 methods covered in this book, plus a brief summary of its use, and one example for each. (Methods that require a bit more explanation—such as line and area generators, geographic projections, layouts, and scale-specific methods—have been omitted.)

Selections

d3.select()

Returns a reference to the first element found:

// Selects an SVG element and stores a reference to it in 'svg'
var svg = d3.select("svg");
d3.selectAll()

Returns references to all found elements:

// Selects all circle elements and stores references to them in 'circles'
var circles = d3.selectAll("circle");
selection.append()

Takes a selection, creates a new element inside of it, then returns a reference to the newly created element:

// Creates a new circle inside of the 'svg' selection established earlier
d3.select("svg").append("circle");

// This would accomplish the same thing…
svg.append("circle");

// …but it's often useful to store a reference to the new element
var newCircle = svg.append("circle");
selection.remove()

Takes a selection, removes it from the DOM, and returns a reference to the deleted selection:

// Removes the first rect element
d3.select("rect").remove();
selection.text()

Takes a selection, sets its text content, and returns a reference to the acted-upon selection:

// Sets the text content of #tooltip to "15%"
d3.select("#tooltip").text("15%");
selection.attr()

Takes a selection, sets an attribute value, and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required