Skip to content

D3.js - Selections

Selections are a fundamental concept in D3.js. They allow you to select existing DOM (Document Object Model) elements from your webpage using CSS selectors. Once elements are selected, D3 provides a powerful API to modify their attributes, styles, content, and even append or remove elements, often in relation to a dataset. Understanding selections is key to mastering D3.

D3.js offers two primary methods for selecting elements:

  • d3.select(selector): Selects the first DOM element that matches the specified CSS selector. If multiple elements match, only the first one encountered in the document is returned in the selection.
  • d3.selectAll(selector): Selects all DOM elements that match the specified CSS selector. This returns a selection containing all matching elements, or an empty selection if no elements match.

If you’re familiar with jQuery selectors, D3.js selectors work similarly.

The d3.select() method uses standard CSS selectors to find elements. You can select by:

  • Tag name: e.g., div, h1, p, span.
  • Class name: e.g., .my-class (prefixed with a dot).
  • ID: e.g., #my-id (prefixed with a hash).

Let’s explore examples for each.

To select the first <div> element on the page:

const firstDiv = d3.select("div");

Example: Modifying the text of the first div.

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div>Original Text 1</div>
<div>Original Text 2</div>
<script>
d3.select("div").text("Hello from D3! This was the first div.");
</script>
</body>
</html>

In a browser, only the first div’s content will change.

To select an element with a specific class, use a dot . prefix.

// Selects the first element with class 'myclass'
const myElement = d3.select(".myclass");

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<p>Another paragraph.</p>
<div class="myclass">Text in myclass div.</div>
<span class="myclass">Text in myclass span.</span>
<script>
d3.select(".myclass").style("color", "blue"); // Only the div will turn blue
</script>
</body>
</html>

IDs should be unique within an HTML document. Select an element by its ID using a hash # prefix.

// Selects the element with ID 'uniqueElement'
const uniqueElem = d3.select("#uniqueElement");

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div id="greeting">Hello World!</div>
<script>
d3.select("#greeting").html("**Greetings from D3!**");
</script>
</body>
</html>

D3 selections provide methods like .append() and .text() (or .html()) to add new elements to the DOM or modify their content. These methods often return the new selection, allowing for method chaining.

The .append(name) method appends a new element with the given tag name (e.g., ‘div’, ‘span’, ‘svg:rect’) as the last child of each selected element. It returns a new selection containing the appended elements.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">Container div.</div>
<script>
d3.select("div.container").append("span");
// This adds an empty <span> inside the div.
// The HTML becomes: <div class="container">Container div.<span></span></div>
</script>
</body>
</html>

The .text(value) method sets the text content of the selected elements. If value is a constant, all selected elements get the same text. If value is a function, it’s evaluated for each selected element.

Chaining .append() and .text():

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="message">Initial message.</div>
<script>
d3.select("div.message")
.append("span") // Appends a span, returns selection of the span
.text(" -- Added by D3.js"); // Sets text of the new span
</script>
</body>
</html>

This results in: <div class="message">Initial message.<span> -- Added by D3.js</span></div>.

D3.js extensively uses method chaining. The same script without chaining would be:

const messageDiv = d3.select("div.message");
const newSpan = messageDiv.append("span");
newSpan.text(" -- Added by D3.js");

D3 provides methods like .html(), .attr(), and .style() to modify the content, attributes, and styles of selected elements.

The .html(value) method sets the inner HTML content of selected elements. Be cautious when using this with untrusted user-provided content due to potential XSS vulnerabilities.

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="content">Placeholder</div>
<script>
d3.select(".content").html("New **HTML** content from D3.js");
</script>
</body>
</html>

The .attr(name, value) method sets the attribute name to the specified value for all selected elements. If value is null, the attribute is removed.

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<a href="#old-link">Old Link</a>
<script>
d3.select("a").attr("href", "https://d3js.org").attr("target", "_blank");
</script>
</body>
</html>

The .style(name, value[, priority]) Method

Section titled “The .style(name, value[, priority]) Method”

The .style(name, value) method sets the CSS style property name to the specified value. An optional priority (e.g., “important”) can be given.

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<p class="highlightable">This paragraph will be styled.</p>
<script>
d3.select(".highlightable")
.style("color", "red")
.style("font-weight", "bold");
</script>
</body>
</html>

The .classed(names, active) method is specifically for managing CSS classes. names is a string of space-separated class names. active is a boolean: true to add the classes, false to remove them. If active is a function, it’s evaluated for each element.

  • Add class: d3.select(".my-element").classed("active highlighted", true);
  • Remove class: d3.select(".my-element").classed("active", false);
  • Check if class exists (on first element): const isActive = d3.select(".my-element").classed("active");
  • Toggle class: element.classed("toggled-class", !element.classed("toggled-class"));

The d3.selectAll(selector) method selects all elements that match the selector. When you apply modification methods (like .attr(), .style(), .text()) to a selection returned by d3.selectAll(), the changes are applied to every element in that selection.

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.item { padding: 5px; margin: 2px; border: 1px solid #eee; }
</style>
</head>
<body>
<div class="item">Item 1</div>
<p class="item">Item 2 (paragraph)</p>
<div class="item">Item 3</div>
<script>
d3.selectAll(".item")
.style("background-color", "lightblue")
.append("strong")
.text(" - Processed!");
</script>
</body>
</html>

In this example, all elements with the class item (two divs and one p) will get a light blue background, and have ” - Processed!” in bold appended to their content.

Selections are the gateway to D3’s data-binding capabilities, where these DOM manipulations become data-driven, forming the heart of D3’s power.