English 中文(简体)
D3.js - Selections
  • 时间:2024-11-03

D3.js - Selections


Previous Page Next Page  

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 visuapzations.

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 famipar 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. span, 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 “span” tag elements,


d3.select(“span”)

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>
      <span>
         Hello World!    
      </span>
      
      <script>
         d3.select("span").text();
      </script>
   </body>
</html>

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