D3 Selections

Learn how the D3 select() and selectAll() methods work on DOM elements.

We'll cover the following

Selection is a fundamental concept used in D3.js. It is used to select DOM elements and manipulate them. In D3.js, we have the following two methods for selection:

  • select() method
  • selectAll() method

select() method

Let’s learn about select(), one of the methods used for selection. It is very powerful, as we will see in the upcoming lessons. It is used to select different HTML tags and manipulate them. If the specified tag is not present, then it will return an empty selection. If multiple instances of the selected tag are present, then it will select the first element only.

Let’s run the famous “hello world” program for D3.js using the select() method.

Console
Code for "hello word" using the 'select' method.

In the above example, from line 1 to line 2, we select the div's content by calling the select() method. This content is stored in a variable s. By pressing RUN, it shows us hello world on the console.

selectAll() method

Let’s explore another method, selectALL(), which is used for selection in D3.js. It is used to select multiple instances of an HTML tag and manipulate them. If the tag is missing, then it will return an empty selection. If multiple instances of the tag are present, then it will select all of them.

Let’s have a look at the following example to see the selectAll() method in action.

Code of the 'selectAll' method.

In line 1 in the above example, we selected all the HTML div tags using the selectAll() method to change their color to green.

We have used the style() method to add style to our text using the selectAll method. Don’t worry; we will explore the style() method in detail in the upcoming lessons.