D3.js – Selections


D3.js – Selections



”;


Selections is one of the core concepts in D3.js. It is based on CSS selectors. It allows us to select one or more elements in a webpage. In addition, it allows us to modify, append, or remove elements in a relation to the pre-defined dataset. In this chapter, we will see how to use selections to create data visualizations.

D3.js helps to select elements from the HTML page using the following two methods −

  • select() − Selects only one DOM element by matching the given CSS selector. If there are more than one elements for the given CSS selector, it selects the first one only.

  • selectAll() − Selects all DOM elements by matching the given CSS selector. If you are familiar with selecting elements with jQuery, D3.js selectors are almost the same.

Let us go through each of the methods in detail.

The select() method

The select() method selects the HTML element based on CSS Selectors. In CSS Selectors, you can define and access HTML-elements in the following three ways −

  • Tag of a HTML element (e.g. div, h1, p, span, etc.,)
  • Class name of a HTML element
  • ID of a HTML element

Let us see it in action with examples.

Selection by Tag

You can select HTML elements using its TAG. The following syntax is used to select the “div” tag elements,


d3.select(“div”)

Example − Create a page “select_by_tag.html” and add the following changes,


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

   <body>
      <div>
         Hello World!    
      </div>
      
      <script>
         d3.select("div").text();
      </script>
   </body>
</html>

By requesting the webpage through the browser, you will see the following output on the screen −