D3.js data joins: add, update, and remove SVG bars with `.join()`
A D3 data join connects an array of data to selected DOM elements: it creates elements for new data, updates matched elements, and removes elements no longer needed. With a unique, stable key in `.data(data, key).join(...)`, D3 can keep a record matched to the same SVG element even when array order changes. This example uses the D3 v7 browser bundle from the official Getting Started guide. It assumes each row has a unique `id`, one category, and a non-negative value; documentation checked 2026-11-18.
D3.js data joins: add, update, and remove SVG bars with .join()
A D3 data join connects an array of data to selected DOM elements: it creates elements for new data, updates matched elements, and removes elements no longer needed. With a unique, stable key in .data(data, key).join(...), D3 can keep a record matched to the same SVG element even when array order changes. This example uses the D3 v7 browser bundle from the official Getting Started guide. It assumes each row has a unique id, one category, and a non-negative value; documentation checked 2026-11-18.
Why join data to elements?
The browser DOM contains the SVG elements currently on screen; your data array contains the values you now want to show. Suppose sales data changes from Alpha, Beta, Gamma to Alpha, Gamma, Delta. The chart needs to update Alpha and Gamma, remove Beta, and add Delta. A D3 join matches elements to data so you do not have to implement those cases manually.
| Join state | Meaning | Bar-chart action |
|---|---|---|
| Enter | Data has no matching element | Create a new <rect> for the category |
| Update | Data matches an existing element | Set the bar’s new position and height |
| Exit | An element has no corresponding new data | Remove the obsolete <rect> |
Without a key function, D3 matches by array index. If order changes, an existing element can end up representing a different category. A stable identifier such as id matches by record identity instead. Keys must be unique. Categories in this example are unique too; if multiple rows share a category, aggregate them first or design a separate position for each row.
Run the D3 v7 example
The official D3 guide shows the browser bundle https://cdn.jsdelivr.net/npm/d3@7. Save the following as index.html and open it in a browser with network access so it can load the CDN script. The values are illustrative, not real sales data.
<!doctype html>
<meta charset="utf-8">
<button id="update">Toggle data</button>
<div id="chart"></div>
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<script>
const width = 520;
const height = 320;
const margin = {top: 20, right: 20, bottom: 45, left: 50};
const first = [
{id: "a", category: "Alpha", sales: 18},
{id: "b", category: "Beta", sales: 11},
{id: "c", category: "Gamma", sales: 24}
];
const second = [
{id: "a", category: "Alpha", sales: 27},
{id: "c", category: "Gamma", sales: 16},
{id: "d", category: "Delta", sales: 21}
];
const svg = d3.select("#chart")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", `0 0 ${width} ${height}`);
const gx = svg.append("g");
const gy = svg.append("g")
.attr("transform", `translate(${margin.left},0)`);
function draw(data) {
const x = d3.scaleBand()
.domain(data.map(d => d.category))
.range([margin.left, width - margin.right])
.padding(0.15);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.sales)])
.nice()
.range([height - margin.bottom, margin.top]);
svg.selectAll("rect.bar")
.data(data, d => d.id)
.join(
enter => enter.append("rect").attr("class", "bar"),
update => update,
exit => exit.remove()
)
.attr("x", d => x(d.category))
.attr("y", d => y(d.sales))
.attr("width", x.bandwidth())
.attr("height", d => y(0) - y(d.sales))
.attr("fill", "steelblue");
gx.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x));
gy.call(d3.axisLeft(y));
}
let showingSecond = false;
draw(first);
d3.select("#update").on("click", () => {
showingSecond = !showingSecond;
draw(showingSecond ? second : first);
});
</script>Click Toggle data. Alpha and Gamma keep their IDs, so their bars update. Beta exits and is removed; Delta enters and is created. The x-domain and y-range are recalculated from the new data, and both axes are called again. A join does not update scales or axes automatically; recalculate them when the data changes.
What .data() and .join() do
.data(data, d => d.id) compares the selected elements with the new array by key and determines the update, enter, and exit sets. D3 binds each data object to its element, making it available as d in later attribute callbacks. .join(...) merges the enter and update selections and handles elements returned by the exit callback. The explicit callbacks in this example make create, keep, and remove behavior visible. For a simpler case, .join("rect") is shorthand: the default update is unchanged and the default exit is removed.
Without a key, matching is by index. If a new category takes an old category’s index, the DOM node may be reused for a different record. An unstable or duplicate id can also cause incorrect matches; clean the data first. Rebuilding every element from scratch can look shorter, but it does not preserve element identity or clearly manage additions and removals.
Verify and troubleshoot
**The chart does not change when you click:** confirm the handler calls `draw` with the other array. If data changes elsewhere, call `draw` after that change too.
**Bars move to the wrong category or values swap:** check that `id` exists, is unique, and remains stable in `.data(data, d => d.id)`. Without it, D3 matches by index.
**Bars change but the axis is stale:** set each scale’s domain from the new data and call the axis generators again on every render.
**A bar has a negative height or disappears:** the example assumes sales are non-negative. Negative values need a zero baseline and separate bar-direction logic. Empty data also needs explicit handling because `d3.max` returns no maximum.
**The console says `d3` is undefined:** confirm the CDN script loads before the chart code. For offline use, the official guide also provides a local D3 v7 bundle.
For development, the official d3@7 URL selects the v7 major line; for reproducible production builds, pin a specific release tested by your project. This code was checked against the API docs but was not run in a browser.
Sources
[D3 Documentation: Joining data](https://d3js.org/d3-selection/joining)
[D3 Documentation: Getting started](https://d3js.org/getting-started)
[D3 Documentation: Band scales](https://d3js.org/d3-scale/band)
[D3 Documentation: Linear scales](https://d3js.org/d3-scale/linear)
[D3 Documentation: d3-axis](https://d3js.org/d3-axis)