Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 44 ยท Selections and Data Joins

Selecting Elements with d3.select

Master D3 selections: select and selectAll, CSS selectors, attr, style, classed, text, html and property, method chaining.

A selection is D3's central object: an array-like group of elements plus a set of methods to change them. If you have used jQuery, the idea is familiar. If you have not, think of it as "find these elements, then tell all of them what to do". Every data-driven chart starts with a selection, so it pays to know it well.

select and selectAll

d3.select(selector) returns a selection of the first element that matches a CSS selector. d3.selectAll(selector) returns all matches, in document order.

JavaScript
d3.select("#chart");          // one element by id
d3.select("svg");             // the first <svg>
d3.selectAll("circle");       // every <circle>
d3.selectAll(".bar.active");  // elements with both classes
d3.select(document.body);     // you can also pass a node
d3.selectAll([elA, elB]);     // or an array of nodes

If nothing matches, select returns an empty selection, not an error. You can ask how many elements you hold with selection.size(), test with selection.empty(), and get the raw nodes with selection.nodes() (all) or selection.node() (the first).

Changing elements: the setters

Selections have a handful of setter methods. Each applies to every element in the selection and returns the selection itself, so calls can be chained.

Method Sets Example
.attr(name, value) An HTML or SVG attribute .attr("r", 5)
.style(name, value) An inline CSS property .style("fill", "red")
.classed(names, bool) Adds or removes a class .classed("active", true)
.property(name, value) A DOM property (such as checked or value) .property("checked", true)
.text(value) The text content .text("Hello")
.html(value) The inner HTML .html("<b>Hi</b>")

Called with only a name, attr, style and property act as getters and return the first element's value. .classed("active") returns a boolean. .text() returns the text.

Setters and getters

attr versus style matters in SVG. Presentation attributes such as fill="red" have lower priority than CSS rules, so a stylesheet can override them. .style("fill", "red") sets an inline style and wins over most stylesheet rules. For values you want to control from CSS, set a class and style it in a stylesheet.

Accessor functions: values that depend on the data

Every setter accepts either a constant or a function. A function is called once per element with three arguments: the bound datum d, the element's index i, and the group nodes. Inside, this is the DOM element, so use a regular function (not an arrow) if you need this.

JavaScript
selection.attr("cx", (d, i) => 30 + i * 40);
selection.style("fill", function(d) { return d.hot ? "tomato" : "teal"; });
selection.text(function() { return this.tagName; });

Without data bound, d is undefined, but the index i still works. The next lesson, Binding Data, puts real data behind d.

Index-based styling

Chaining and indentation

Because setters return the selection, you chain them. The D3 convention is one method per line, with a two-space indent:

JavaScript
d3.select("svg")
  .selectAll("circle")
  .attr("r", 5)
  .style("fill", "teal");

Not every method returns the same selection. select, selectAll, append and insert return a new selection (the children), so the chain moves "down" the tree. Keep that in mind; when a chain gets confusing, store intermediate selections in variables.

each, call, filter and friends

  • selection.each(function(d, i, nodes) {...}) runs a function for every element; use it for custom logic.
  • selection.filter(selectorOrFn) keeps only matching elements: circles.filter(d => d > 10) or .filter(":nth-child(odd)").
  • selection.call(fn, ...args) calls fn(selection, ...args) and returns the selection. It is the standard way to apply reusable pieces such as axes.
  • selection.empty() and selection.size() check the contents.
  • selection.node() returns the first DOM node so you can use native APIs such as getBBox().
each, filter and call

Scoped selection and sub-selections

selection.select(selector) runs querySelector inside each element and returns a selection of the same shape, which is important because it propagates data from parent to child. selection.selectAll(selector) finds descendants and groups them by parent, which is the basis of nested selections. To search inside one element only, chain from it: d3.select("#chart").selectAll("rect") finds rectangles within #chart rather than the whole page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does d3.select('.bar') return if there are five elements with class bar?

    select picks the first match. Use selectAll to get all of them.
  2. 2. In .attr('cx', (d, i) => i * 10), what is i?

    The accessor receives the datum, the index and the node list. The index counts elements in the group starting at 0.
  3. 3. Why use a regular function instead of an arrow function when you need 'this' inside a D3 callback?

    D3 calls the callback with this set to the DOM element. Arrow functions capture this from the surrounding scope instead.
  4. 4. Which method is the idiomatic way to apply a reusable function (like an axis) to a selection?

    call(fn) invokes fn(selection) and returns the selection, so reusable components chain nicely.

Summary

  • d3.select returns the first match, d3.selectAll all matches; empty selections are not errors.
  • Setters (attr, style, classed, property, text, html) apply to every element and return the selection; with one argument most work as getters.
  • Pass a function (d, i, nodes) instead of a constant to compute values per element.
  • Use each, filter, call, size, empty and node for control flow and reuse.

Next: Adding, Removing and Reordering Elements