liveBook · Manning

D3.select

As explained in D3.js in Action, Third Edition

d3.select is a D3 method that returns a selection containing the first DOM element matching a selector.

d3.select() starts DOM manipulation by returning a D3 selection containing the first element that matches a CSS-style selector. The selection is ready for chained operations such as append(), attr(), and style(). section 2.3 section 2.7

Pass familiar CSS selector forms to identify one element:

  • Use a tag name, such as d3.select("h1"). section 2.3
  • Use a class or ID, such as d3.select(".intro") or d3.select("#viz-container"). section 2.3
  • Combine selectors with CSS syntax, such as d3.select("#viz-container p"), or chain selections with .select("p"). section 2.3
  • Remember that d3.select("circle") returns only the first matching circle; use d3.selectAll() when several elements are needed. section 2.3
d3.select("h1");

A minimal selection makes the API’s selector argument and single-element focus immediately visible. section 2.3

Add an SVG container

Select the existing .responsive-svg-container element and append an SVG element: d3.select(".responsive-svg-container").append("svg");. The browser may show no immediate change, but the SVG appears in the DOM and can then receive attributes or child shapes. section 2.4

Build a circle pack

Import select from d3-selection, select #circle-pack, append an SVG and group, then continue the chain with selectAll(), data(), and join("circle") to draw the chart’s circles. section 11.2.2

How D3.js in Action, Third Edition covers it

How deep it goes
Defines selector syntax, first-match behavior, chaining, and SVG construction, but defers multi-element selection to selectAll().
Examples
Uses headings, classes, IDs, nested paragraphs, responsive SVG containers, and circle-pack chart elements.
What it assumes
Assumes basic DOM and CSS selector familiarity while demonstrating selector forms through concrete HTML and visualization examples.
What you can do after
Apply it via D3 to select chart containers, append SVG elements, and begin chained visualization construction.
How it connects
Connects CSS selectors, DOM manipulation, method chaining, selectAll(), append(), SVG, and data binding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.