D3.js Selections in JavaScript: A Complete Tutorial
- Samul Black

- Apr 11
- 4 min read
Updated: Aug 18
One of the core features that makes D3.js such a powerful data visualization library is its ability to select and manipulate HTML or SVG elements based on data. At the heart of this capability lies the concept of a selection.
This tutorial will introduce you to D3.js selections, explain how they work, and show you how to use them to dynamically manipulate elements on a web page. Whether you're just beginning with D3 or looking to solidify your foundation, understanding selections is a crucial first step toward creating interactive and data-driven visualizations.

What is a Selection in D3.js?
In D3.js, a selection refers to a group of DOM elements that can be manipulated using D3’s wide range of methods. While this may sound similar to JavaScript’s document.querySelectorAll() or jQuery’s $(), D3’s selection mechanism is far more powerful due to its tight integration with data.
Unlike standard DOM selection tools, D3 selections are data-aware. They allow you to bind datasets directly to visual elements, enabling highly dynamic and interactive visualizations. This approach makes it easy to build charts and graphs that respond to real-time data or user interactions.
Key Features of D3 Selections:
Element Selection:Use methods like d3.select() or d3.selectAll() to target HTML or SVG elements.
Data Binding:Link external data to elements using .data() so that you can drive the visualization directly from the dataset.
Enter-Update-Exit Pattern:Dynamically add, update, or remove DOM elements based on changes in the bound data.
Chained Operations:Apply styles, attributes, text, or event listeners in a clean and concise manner using method chaining.
Declarative Style:Express what should happen to each element, instead of explicitly coding how to manipulate it step-by-step.
Why Selections Matter:
They serve as the foundation of every D3 visualization, from simple bar charts to complex multi-layered dashboards.
Selections connect data to visuals, enabling reactive updates and transitions.
They make it easy to scale visualizations by automatically applying changes across entire datasets.
In essence, D3 selections are not just about picking elements—they’re about creating a living link between your data and the DOM, empowering you to build visualizations that are as flexible and insightful as the data itself.
Including Javascript library D3.js in Your Project
Before you can use D3, you need to include the library in your HTML file. The simplest way is to use a CDN (Content Delivery Network) link:
<script src="https://d3js.org/d3.v7.min.js"></script>This allows you to start using D3.js immediately without any additional setup.
A Basic HTML Setup
Let’s begin with a simple HTML structure that includes a few paragraph elements:
<body>
<h2>D3 Selection Example</h2>
<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<p class="text">Paragraph 3</p>
</body>We’ll use this as our starting point for working with selections.
Selecting Elements with D3
To select a single element, D3 provides the d3.select() function.
d3.select("p").style("color", "red");Output:

Selecting a Single Element
This function selects the first element that matches the specified selector.
This code selects the first <p> element on the page and changes its text color to red.
d3.selectAll("p").style("color", "blue");
Selecting Multiple Elements
To select all elements that match a selector, D3 provides the d3.selectAll() function.
This changes the text color of all paragraph elements to blue as shown in the image.
Chaining Methods
D3 allows you to chain multiple methods together for a cleaner and more expressive syntax.
Example:
d3.select("p")
.style("color", "green")
.attr("class", "highlight")
.text("Updated Text");
This line of code changes the text color to green, sets the class attribute to "highlight", updates the text content to "Updated Text".
All of this is done on the first <p> element that was selected.
Binding Data to Elements
One of D3’s most powerful features is its ability to bind arrays of data directly to DOM elements. The .data() method is used to associate an array with the selected elements.
Example:
const data = ["Apple", "Banana", "Cherry"];
d3.selectAll("p")
.data(data)
.text(function(d) {
return d;
});
This code binds the array to the three <p> elements and updates their content to display each fruit name accordingly.
Updating and Removing Elements
D3 can also update existing elements and remove those that are no longer needed. This is done using the enter-update-exit pattern.
Example:
const numbers = [10, 20,43,43];
const selection = d3.select("body")
.selectAll("p")
.data(numbers);
// Update existing elements
selection.text(function(d) {
return "Value: " + d;
});
// Create new elements for new data
selection.enter()
.append("p")
.text(function(d) {
return "New: " + d;
});
// Remove elements that no longer have data
selection.exit().remove();Output:

This example shows a typical use of the enter-update-exit pattern:
Existing elements are updated with new values,
New elements are created when there’s more data than elements,
Unused elements are removed when there’s less data than elements.
Summary of Common Selection Methods
Below is a quick reference list of commonly used D3 selection methods:
d3.select(selector) – Selects the first matching element.
d3.selectAll(selector) – Selects all matching elements.
.data(array) – Binds an array of data to the selected elements.
.enter() – Handles data without corresponding DOM elements (used to create new elements).
.append(tag) – Adds a new element to the DOM.
.text(function) – Sets or returns the text content of selected elements.
.attr(attribute, value) – Sets or gets an attribute.
.style(property, value) – Sets or gets a CSS style.
.exit() – Selects DOM elements that no longer have associated data.
Conclusion
D3.js selections form the foundation of virtually every data visualization you’ll create with the library. By learning how to select and manipulate DOM elements based on data, you open the door to building highly dynamic and interactive graphics. Whether you're modifying existing elements, creating new ones based on fresh data, or cleaning up unused DOM nodes, selections are the key tool that enables D3's powerful data-driven paradigm. Mastering them sets the stage for deeper exploration into scales, layouts, animations, and more complex visual storytelling.
If you're ready to go further, the next step is to learn how to use scales to map data to visual properties, or explore transitions for animating your updates. The world of D3 is vast and rich with possibilities, and it all starts with selections.




