D3 and the DOM

Objectives

  • Select elements in the DOM using d3.select and d3.selectAll

  • Set attributes, inner text, and style properties on D3 selections

  • Get attribute and property values on D3 selections

  • Chain D3 methods together to make more complex changes to the DOM

  • Pass callback functions into D3 selection methods for more dynamic behavior

  • Add event listeners using the 'on' method

  • Use d3.event to access the event object inside of an event listener

  • Add and remove DOM elements with D3

D3 Selections

Loading D3

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Your awesome title</title>
</head>
<body>
  <!-- HTML goes here - check the links for an example! -->
  <script src="https://d3js.org/d3.v4.js"></script>
</body>
</html>

Selection Methods

  • d3.select - single element
  • d3.selectAll - multiple elements
  • both accept a valid CSS selector
  • selection.nodes() - return an array of matching HTML elements
  • selection.node() - return the first (non-null) HTML element.

Accessing Nodes

selection.style(property [, newValue])

Manipulating Selections

style, attr, text, and html methods

selection.attr(attribute [, newValue])

selection.text([newValue])

selection.html([newValue])

Note: These (and other!) D3 methods will work as getters if no newValue is passed in.

Manipulating Selections

classed method

selection.classed(classList [, shouldClassesBeSet])

space-separated list

checks whether classes should be added or removed

Selections and Callbacks

Code Example

selection.style(property [, newValue])

selection.attr(attribute [, newValue])

selection.text([newValue])

selection.html([newValue])

Selections and Callbacks

selection.style(property [, callback])

selection.attr(attribute [, callback])

selection.text([callback])

selection.html([callback])

The callback will be invoked once for each element in the selection.

Callback Structure

function (_, idx) {
  // write your code here
}

Don't worry about the first argument for now.

Index of the current element in the selection.

Event Listeners in D3

Code Example

Adding event listeners

selection.on(eventType, callback)

Type of event

Code to run when event is triggered

The Event Object

d3.event

This property on d3 will contain all of the event information when referenced inside of an event handler.

Appending Elements

append method

selection.append(tagName)

Appends a new element of type tagName to every element in the selection.

Returns a new d3 selection.

Accessing Properties

property method

selection.property(name [, newValue])

Access a property (e.g. an input value) which is not accessible as an element attribute.

Removing Elements

remove method

selection.remove()

Remove the selection from the DOM.

YOUR

TURN

D3 and the DOM

By Elie Schoppik

D3 and the DOM

Introduction to DOM manipulation with D3

  • 1,709