Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 44 ยท Selections and Data Joins

Adding, Removing and Reordering Elements in D3

Create and remove DOM and SVG elements with D3: append, insert, remove, clone, raise, lower, order, sort, merge and join, plus when to use each method.

Selecting existing elements is only half the job. A chart builds its own elements, so you need to create them, put them in the right place, and remove them. D3 provides small methods for each step. Knowing them makes later topics like the data join easy to follow.

append and insert

selection.append(name) adds a new child as the last child of each selected element and returns a selection of the new children. The name can be a tag ("circle", "div"), and D3 uses the right namespace automatically, so append("rect") inside an <svg> creates a real SVG rectangle.

selection.insert(name, before) adds the new child before a given sibling instead (a selector string or a function that returns a node).

JavaScript
const svg = d3.select("svg");
svg.append("rect");                 // last child
svg.insert("rect", ":first-child"); // first child: it will be painted underneath

Because append returns the new element, you can keep chaining to style it:

JavaScript
svg.append("g")
  .attr("class", "plot")
  .append("circle")
  .attr("r", 10);

The second .append and .attr apply to the circle, not to the group. To keep working on the group, store it in a variable first.

append and insert

remove, raise, lower and order

  • selection.remove() removes every selected element from the document and returns the (now detached) selection.
  • selection.raise() re-appends each element so it becomes the last child, i.e. painted on top. SVG has no z-index, so this is how you bring a hovered bar to the front.
  • selection.lower() moves each element to be the first child, painting it at the bottom.
  • selection.order() rearranges elements in the DOM to match the order of the selection (useful after a data join with new data order).
  • selection.sort(compare) sorts the elements by their data and reorders them in the DOM. selection.sort(d3.ascending) works for numeric data.
  • selection.clone(deep) duplicates each element, inserting the copy right after the original.
raise, lower, remove and sort

Notice that raise and lower change only the order in the DOM; positions stay the same. The painted result changes because later elements cover earlier ones.

text and html versus append

You will meet three ways to put content into elements:

Goal Use
Put plain text in an element .text("...") (safe, escapes HTML)
Put markup in an element .html("<b>..</b>") (never with untrusted input)
Create child elements .append("tag") or a join

Setting .text() replaces all children of the element, which is fine for labels. If you pass untrusted strings (user input, API data) to .html(), you open an XSS hole, so prefer .text() and .append().

Creating detached elements

d3.create("svg") makes a new element not attached to the page and returns a selection of it. That is handy for building a chart inside a function and returning the node, which the caller inserts wherever it wants.

JavaScript
function makeChart(data) {
  const svg = d3.create("svg").attr("viewBox", [0, 0, 400, 200]);
  svg.selectAll("rect").data(data).join("rect")/* ... */;
  return svg.node();           // a real <svg> element
}
document.body.append(makeChart([1, 2, 3]));

d3.creator("svg") and selection.append(() => node) take this further, but d3.create is what you will use 90% of the time.

d3.create builds a detached chart

merge and clone

selection.merge(other) combines two selections of the same group structure into one, preserving order. You will use it in the enter-update-exit pattern to apply common attributes to new and existing elements together. selection.clone(true) deep-copies elements including descendants, for repeating a template.

Avoid creating elements inside a loop that runs on every redraw without removing the old ones. If you call svg.append("circle") each time a button is clicked, circles pile up. The data join (next lessons) exists to prevent exactly that: it creates, updates and removes elements to match your data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method makes an SVG element paint on top of its siblings?

    SVG paints in document order, so raise() re-appends the element as the last child. SVG has no z-index property.
  2. 2. After svg.append('g').append('circle'), what does the returned selection hold?

    append returns a selection of the newly created children, so the second append returns the circle.
  3. 3. Why prefer .text() over .html() for data coming from users?

    html() parses markup and can enable XSS. text() inserts the value as plain text.
  4. 4. What does d3.create('svg') return?

    d3.create builds a detached element wrapped in a selection. Use .node() to get the element and attach it where needed.

Summary

  • append adds last children, insert adds before a sibling, remove deletes, and clone copies.
  • raise, lower, order and sort control DOM order, which controls painting order in SVG.
  • text is safe for strings; html parses markup, so avoid it with untrusted input.
  • d3.create makes detached elements for reusable chart functions; merge combines selections.

Next: Binding Data to Elements