Selections

Learn how to select elements in the document with D3.

Selections are objects that represent an element in the document.
A selection will give us the power to perform operations such as adding, deleting, and modifying elements.

How to make a selection

In the browser, there are already a set of functions for selecting elements. The native browser functions can also add, delete, or modify elements. The document.querySelector() function is an example of a function that is already available. Regardless, D3 provides its own version of a function that can select an element called d3.select().

It works similarly to the native browser functions. It is not exactly clear when you should want to use the D3 function instead of the regular function defined by the browser. Let’s explore the differences between the two functions to better understand their specific uses.

Regardless of which function you use, the ultimate goal of selecting an element is being able to read its properties or change them. By selecting an element, we will be able to perform actions, such as changing its CSS properties or inserting new elements. Here is an example of how selections can be made with both the browser’s functions and D3.

Get hands-on with 1200+ tech skills courses.