Code

D3.js

Select & Style

Beginner Use d3.select() and d3.selectAll() to target elements and apply attributes, styles, and properties. d3-selection

import * as d3 from 'd3';

const svg = d3.select('#container')
  .append('svg')
  .attr('viewBox', '0 0 480 300')
  .attr('width', '100%');

// Append coloured circles
const colours = ['#4f46e5','#e11d48','#16a34a','#f59e0b','#0ea5e9'];
colours.forEach((c, i) => {
  svg.append('circle')
    .attr('cx', 60 + i * 90)
    .attr('cy', 80)
    .attr('r', 35)
    .attr('fill', c);
});

// Select ONE element and style it
svg.select('circle')
  .attr('stroke', '#111')
  .attr('stroke-width', 3)
  .attr('stroke-dasharray', '6,3');

// Select ALL and add title tooltips
svg.selectAll('circle')
  .append('title')
  .text(function() {
    return `fill: ${d3.select(this.parentNode).attr('fill')}`;
  });
Key APIs
  • d3.select(selector) — selects the first matching element
  • d3.selectAll(selector) — selects all matching elements
  • .attr(name, value) — sets an SVG/HTML attribute
  • .style(name, value) — sets a CSS style property
  • .append(tag) — appends a child element and returns a selection of it
  • .text(value) — sets the text content