Chapter 12. Selections

Your first taste of a D3 selection was simple, and involved only one element: d3.select("body"). Then you learned about selectAll() for selecting multiple elements. When we introduced binding data to elements, you learned about the now-familiar selectAll/data/enter/append pattern for creating new elements. Later, you saw how to use merge() to combine selections (such as when applying updates to a chart) and exit() to select elements on their way out. In Chapter 11, you saw examples of how datum() could be used to bind data to a single element, bypassing the usual data join process.

For many visualizations, that’s all you’ll need to know. But as you begin to dream up more complex and interactive pieces, a deeper understanding of selections and how you can manipulate them will make your life a lot easier.

Let’s explore some of the possibilities.

A Closer Look at Selections

What is a selection, really? I am here to demystify this concept for you. (Does that make me a demystic?)

Let’s look closely at a very simple selection. Note the result of d3.select("body") in Figure 12-1.

dvw2 1201
Figure 12-1. A simple selection

So, a selection contains two arrays, _groups and _parents. We can disregard _parents and also the __proto__ object, which is an essential feature of JavaScript’s prototype-based structure and also way beyond the scope of this book.

Let’s expand _groups ...

Get Interactive Data Visualization for the Web, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.