Skip to content

D3.js Selections — Selecting and Manipulating DOM Elements

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about D3.js Selections. We cover key concepts, practical examples, and best practices to help you master this topic.

D3.js selections are the core mechanism for finding DOM elements and applying data-driven transformations through chainable method calls.

What You'll Learn

By the end of this guide, you will use d3.select and d3.selectAll, chain methods fluently, filter selections, manipulate attributes and styles, append and remove elements, and understand the selection lifecycle.

Why Selections Matter

Every D3.js visualization starts with a selection. In Durga Antivirus Pro's performance dashboard, selections update DOM elements representing real-time threat metrics. Without selections, you would write manual DOM loops for every update.

flowchart LR
    A[DOM Element] --> B[d3.select]
    A --> C[d3.selectAll]
    B --> D[Selection Object]
    C --> D
    D --> E[.attr]
    D --> F[.style]
    D --> G[.text]
    D --> H[.append]
    D --> I[.remove]

Basic Selection Methods

d3.select('body')          // Select the <body>
d3.select('#chart')        // Select element with id="chart"
d3.select('.bar')          // Select first element with class="bar"
d3.selectAll('circle')     // Select all <circle> elements
d3.selectAll('.bar')       // Select all elements with class="bar"

Chaining Methods

d3.select('#chart')
    .append('svg')
    .attr('width', 500)
    .attr('height', 300)
    .append('g')
    .attr('transform', 'translate(50, 50)')
    .append('circle')
    .attr('r', 30)
    .attr('fill', 'steelblue');

Expected output: An SVG with a group translated to (50,50) containing a blue circle with radius 30.

Filtering Selections

var circles = d3.selectAll('circle')
    .filter(function(d, i) {
        return i % 2 === 0;  // Only even-indexed circles
    })
    .attr('fill', 'orange');

Appending and Removing Elements

// Append a paragraph
d3.select('body')
    .append('p')
    .text('Hello D3.js');

// Remove all elements with class="old"
d3.selectAll('.old').remove();

Common Mistakes

1. Using select Instead of selectAll for Multiple Elements

d3.select returns only the first match. For multiple elements, always use d3.selectAll.

2. Breaking the Chain

Storing intermediate selections in variables breaks the chain. Chain all operations for clean code.

3. Forgetting That append Returns the Appended Element

After append, the selection changes to the newly created element, not the parent.

4. Using CSS Selectors Incorrectly

D3 selections use CSS selector syntax. d3.select('bar') selects <bar> elements, not elements with class "bar".

5. Not Handling Empty Selections

Methods called on empty selections silently do nothing. Check selection.size() if needed.

Practice Questions

Q1: What is the difference between d3.select and d3.selectAll? A: d3.select returns the first matching element. d3.selectAll returns all matching elements as a group.

Q2: Does d3.selectAll maintain element order? A: Yes. Elements are returned in document order (top to bottom, parent to child).

Q3: What does .append('circle') return? A: A new selection containing the newly created element.

Q4: How do you remove all children of a selection? A: selection.selectAll('*').remove() removes all child elements.

Q5: What happens if you chain methods on an empty selection? A: Each method silently returns the same empty selection. No errors are thrown.

Challenge: Create an HTML list of 10 items. Use D3 selections to color even items blue and odd items red, then change the text of every third item to bold.

FAQ

Can I use jQuery selectors with D3?

No. D3 has its own selector engine. You cannot pass jQuery objects to D3 selection methods.

{{< faq "How do I select by data attribute?" "Use attribute selector: `d3.select('[data-id=\"123\"]')`." >}}
What is a selection object?

A selection is a D3 wrapper around DOM elements with chainable methods. It is not a raw array or NodeList.

How do I iterate over a selection?

Use .each(function(d, i) { ... }) to run a callback for each element in the selection.

Can I store a selection for reuse?

Yes. var svg = d3.select('svg') stores the selection. But chaining is preferred for readability.

Try It Yourself

Build a page with a grid of DIV elements. Use D3 selections to manipulate their appearance with a single chain.

<!DOCTYPE html>
<html>
<head>
    <title>D3 Selections Demo</title>
    <style>
        .grid { display: flex; flex-wrap: wrap; width: 300px; }
        .cell { width: 50px; height: 50px; margin: 2px; background: #eee; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: bold; }
    </style>
</head>
<body>
<div class="grid" id="grid"></div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
d3.select('#grid')
    .selectAll('div')
    .data(d3.range(25))
    .enter()
    .append('div')
    .attr('class', 'cell')
    .text(function(d) { return d + 1; })
    .style('background', function(d) {
        return d % 2 === 0 ? '#4ecdc4' : '#ff6b35';
    })
    .style('color', 'white')
    .style('border-radius', '8px');
</script>
</body>
</html>

What's Next

Master the enter-update-exit pattern for dynamic data.

Enter Exit — The enter-update-exit pattern in D3.js. Transitions — Animated transitions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro