In the previous section, the concepts of Select and SelectAll, as well as selection sets, have been explained. This section explains the use of these two functions in detail.
Suppose there are three paragraph elements in the body:
< P > Apple</p><p>Pear</p > < P > Banana</p>
Now, to complete the task of the following four selection elements separately.
One, select the first P element
With SELECT, the parameter is passed in P, so the first P element is returned.
var bodys = D3.select ("body"); var p = bodys.select ("P"); P.style ("Color", "red");
As a result, the selected element is marked in red.
Second, select three elements
Use SelectAll to select all the P elements in the body.
var p = body.selectall ("P");p. Style ("Color", "red");
The results are as follows:
Third, select the second P element
There are a number of ways, a simple one is to add an ID number to the second element.
<id= "myID">Pear</p>
Then, select the element with select and note the # number before the ID name in the parameter.
var p2 = body.select ("#myid");p 2.style ("Color", "red");
The results are as follows:
Iv. Select the latter two P elements
Add a class to the two elements,
<class= "MyClass">Pear</p> <class= "MyClass">Banana</p >
Because you need to select multiple elements, use SelectAll. Note the parameter, which is a point before the class name.
var p = Body.selectall (". MyClass");p. Style ("Color", "red");
The results are as follows:
The parameters for select and SelectAll are actually in line with the CSS selector's criteria, i.e. the ID is denoted by the "pound sign (#)", and the "dot (.)" is used to denote class.
In addition, for selection sets that already have data bound, there is a way to select elements, which is to use function (d, i) flexibly. We already know that the parameter I represents the index number, so we can use the conditional decision statement to specify the element to execute.
D3.js selecting elements