
Selecting multiple elements
Often selecting a single element is not good enough, but rather you want to apply certain change to a set of elements on the page simultaneously. In this recipe, we will play with D3 multi-element selector and its selection API.
Getting ready
Open your local copy of the following file in your web browser:
https://github.com/NickQiZhu/d3-cookbook/blob/master/src/chapter2/multiple-selection.htmlHow to do it...
This is what the d3.selectAll
function is designed for. In this code snippet, we will select three different div
elements and enhance them with some CSS classes.
<div></div> <div></div> <div></div> <script type="text/javascript"> d3.selectAll("div") // <-- A .attr("class", "red box"); // <-- B </script>
This code snippet produces the following visual:

Multi-element selection
How it works...
First thing you probably would notice in this example is how similar the usage of D3 selection API is when compared to the single-element version. This is one of the powerful design choices of the D3 selection API. No matter how many elements you are targeting, whether one or many, the modifier functions are exactly the same. All modifier functions we mentioned in the previous section can be applied directly to multi-element selection, in other words D3 selection is set-based.
Now with that being said, let's take a closer look at the code example shown in this section, though it is generally pretty simple and self-descriptive. At line A, the d3.selectAll
function is used to select all the div
elements on the page. The return of this function call is a D3 selection object that contains all three div
elements. Immediately after that, on line B, the attr
function was called on this selection to set the class
attribute to red box
for all three div
elements. As shown in this example, the selection and manipulation code is very generic, and will not change if now we have more than three div
elements on the page. This seems to be an insignificant convenience for now, but in later chapters we will show how this convenience can make your visualization code simpler and easier to maintain.