官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 尉氏县| 怀化市| 和田县| 西盟| 资阳市| 奉节县| 四子王旗| 西贡区| 浏阳市| 宜黄县| 盐山县| 万载县| 高邑县| 东安县| 台东县| 罗江县| 安平县| 广水市| 柯坪县| 潜山县| 和硕县| 景宁| 天台县| 静宁县| 黄浦区| 韶关市| 吉木乃县| 柘荣县| 临湘市| 柳河县| 定日县| 蓬莱市| 富源县| 伊春市| 鄂托克旗| 静安区| 渭南市| 筠连县| 双峰县| 鸡西市| 尉犁县|