Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.2 — Selections
Data Visualization · Example 1 of 2

Pick, change, create and delete

A selection is a list of page elements that D3 holds for you. You find elements with select and selectAll, change them with attr, style and text, add with append, delete with remove, and chain the calls. An empty selection is not an error: setters do nothing, and getters throw.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given <ul id="list"><li>Quay</li><li>Market</li><li>Chapel</li></ul>, write the D3 line that gives every li the title Station: <its text> using this, and the line that deletes every li whose text is longer than 5 letters.

02

Write a function labelAll(selector, text) that sets the text of every match and returns how many elements it changed. Check that it returns 0 for a selector that matches nothing and does not throw.

Explain it without notes

01

What is the difference between select and selectAll?

02

What happens when you call attr("x", 5) on a selection that matched nothing? And attr("x")?

03

Why does (d, i, nodes) => this.textContent fail while function (d, i, nodes) { return this.textContent; } works?

Pick, change, create and delete

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

select: 1 selectAll: 3
rows: 0,1,2
first text: Quay
appended: rect 120
after remove: Quay, Chapel
empty: true size: 0 node: null