chapter two

2 Manipulating the DOM

 

This chapter covers

  • Setting up a local development environment for D3 projects
  • Selecting elements from the DOM
  • Adding HTML or SVG elements to a selection
  • Setting and modifying the attributes and styles of DOM elements

Now that we've established the role of D3 and its ecosystem of tools, it is time to get to work! In this chapter, we will set the foundations of our first visualization while learning how to manipulate the DOM (Document Object Model) with D3.

DOM manipulation is at the root of any D3 project, and the techniques that you will learn in this chapter are probably the ones you will use the most often as a D3 developer. First, we will cover selections, which allow us to grab a single or multiple elements from the DOM. You'll see that D3 makes selections very easy and intuitive. Then, once we have a selection, we'll want to do something with it. An action that we regularly perform in D3 projects is adding HTML or SVG elements to a selection. For example, to create a visualization, we often append SVG shapes inside an SVG container. Finally, we adjust the positions, sizes, and colors of these SVG shapes. We do that by setting their attributes and styles.

Because this book focuses on building projects in a local development environment, you'll need to have one before we dive into D3 techniques. In section 2.2, we will explain how to use VS Code and its Live Server extension to have a local environment ready to go within a few minutes.

2.1 Your first D3 visualization

2.2 Preparing your environment

2.2.1 The structure of our first D3 project

2.2.2 Loading D3 into a project

2.3 Selecting elements

2.4 Adding elements to a selection

2.5 Setting and modifying attributes

2.6 Setting and modifying styles

2.7 Summary