Trusted answers to developer questions

What are D3 selections?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

svg viewer

A little about D3

D3 is an interactive JavaScript library for data visualization. It uses Scalar Vector Graphics (SVG) coupled with HTML and CSS to display charts and figures that illustrate numeric data. When making the DOM elements for these charts and figures, the need to edit them often arises. This can be done by selecting, under the <script> tag, the desired elements and then adding the appropriate features to it. After selecting, you can change them, style them, add attributes, or insert/remove elements.

D3 has two functions to make selections: d3.select() and d3.selectAll().

d3.select() selects the first matching element, while d3.selectAll() selects all matching elements. Each function takes a single argument that specifies the selector string. This selector string can be:

  • Tag - "div"
  • Class - ".classA"
  • ID - "#content"

Let’s look at an example:

d3.select()

Observe the code:

<!DOCTYPE html>
<html>
   <head>
      <script src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <h1>
          conatiner 1       
      </h1>
      
      <script>
      </script>
   </body>
</html>

Here, we have a <h1> container that we want to add text to. We can add the text by first selecting the tag using d3.select(), then specifying the selector string as "h1", and finally adding text. We can also add styling attributes.

d3.selectAll()

Observe the code:

<!DOCTYPE html>
<html>
   <head>
      <script src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <h1>
          conatiner 1       
      </h1>
      <h1>
          conatiner 2      
      </h1>
      <h1>
          conatiner 3       
      </h1>
      
      <script>
      </script>
   </body>
</html>

Here, we have three <h1> containers that we want to add text to. We can add that text by first selecting the tags using d3.selectAll(), then specifying the selector string as "h1", and finally adding text. We can also add styling attributes.

RELATED TAGS

d3
select
selectall
selection

CONTRIBUTOR

Shahpar Khan
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?