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 discussed D3’s ecosystem, it’s time to get to work! In this chapter, we’ll set the foundations of our first visualization while learning how to manipulate the document object model (DOM) with D3.
DOM manipulation is a foundational feature of D3, and the techniques that you’ll learn in this chapter are probably the ones you’ll use most often as a D3 developer (as long as you’re not working with a JavaScript framework like React or Svelte, which we’ll discuss in chapter 8). First, we’ll cover selections, which allow us to grab a single element 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 Scalable Vector Graphics (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 by setting their attributes and styles.