liveBook · Manning

Classed()

As explained in D3.js in Action, Third Edition

classed() is a D3 selection method that adds or removes a specified CSS class on each selected element according to a Boolean value.

classed() is a D3 selection method for adding or removing one CSS class without overwriting the selection’s other classes. Pass the class name first and true or false second. section 7.2.2

Unlike attr("class", ...), which replaces the entire class attribute, classed() changes a named class independently. This preserves an existing class such as filter while toggling active. section 7.2.2

Marking the active filter

d3.selectAll(".filter") .classed("active", filter => filter.id === d.id ? true : false); A click callback updates each filter button so only the clicked filter receives the active class, then refreshes the histogram. section 7.2.1

myActiveFilter
  .classed("active", true);

Shows the compact form for adding the active class while retaining the existing filter class. section 7.2.2

How D3.js in Action, Third Edition covers it

How deep it goes
Explains the two arguments, contrasts classed() with attr(), and demonstrates Boolean callbacks for per-element class changes.
Examples
Uses filter buttons, the active class, Boolean expressions, and a histogram refreshed after a click.
What it assumes
Assumes familiarity with D3 selections and attr(), while demonstrating class toggling through a filter-button interaction.
What you can do after
Apply it via D3 to toggle individual CSS classes while preserving other classes on selected elements.
How it connects
Connects CSS classes with D3 selections, attr(), on(), callbacks, data binding, and interactive visualization updates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.