Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d3
select
selectall
selection

What are D3 selections?

Shahpar Khan
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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring