Manipulating the DOM with d3-selection

Every node in a DOM tree comes with a slew of methods and properties that you can use to manipulate the rendered document.

Take, for instance, the HTML code in our preceding example. If we want to change the word italic to make it underlined as well as bold and italic (the result of the <em> and <strong> tags), we would do it using the following code:

document.querySelector('strong').style
.setProperty('text-decoration', 'underline')

document.querySelector finds the first element of a CSS selection and then returns it. We then set underline as the text-decoration property.

Using the modern DOM API is a lot nicer than it used to be, but it's a bit fraught with peril unless you polyfill various functionalities into the browser. We could use jQuery, which gives a nice API for this style of development, or we could use D3, which comes with a similar set of tools for selecting and manipulating the DOM (all contained within the d3-selection microlibrary).

With d3-selection, we can treat HTML as just another type of data visualization. Let that one sink in--we can use our regular old HTML for data visualization.

In practice, this means that we can use similar techniques to present data as a table or an interactive image. Most of all, we can use the same data.

Let's rewrite the preceding example using d3-selection:

import * as d3 from 'd3'; 
d3.select('strong').style('text-decoration', 'underline')

Much simpler! We selected the strong element and defined a style property. Job done!

By the way, any property you set with D3 can be dynamic, so you can assign a function as well as a value; This will come in handy later.

What we just did is called a selection. Selections are the core of everything we do with D3--d3.select is used to select a single element, while d3.selectAll creates an array-like selection with multiple elements. Let's take a look at selections in more detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset