[2.1] How to Select, insert, and delete elements in D3.js

Source: Internet
Author: User

If you are interested in D3.js or data visualization, welcome to www.ourd3js.com for discussion. My blog homepage is: http://blog.csdn.net/lzhlzz, reprinted please indicate the source, thank you.


In D3.js, there are two functions for selecting elements: select and selectAll. First, describe their differences:

  • Select is the first choice for all specified elements.
  • SelectAll is to select all the specified elements (used for subsequent operations at the same time)

Let's look at a specific example. The following code is available:

Friends who are familiar with HTML will surely know what the above Code outputs, which is the title of the three lines of h1 size. If you want to complete two selection tasks: select the first h1 and three h1 at the same time.

The Code is as follows:

Var body = d3.select ("body"); // select the body (the first body, of course, only one body) var h1 = body. select ("h1"); // select the first h1var all_h1 = body. selectAll ("h1"); // select all h1
In order to prove that the above variable h1 is the first h1, all_h1 Selects all h1, we add the Code:

h1.style("color","red");
Color the element selected by the h1 variable. When this clause is added, the result is:

In this way, we can prove that we selected the first element.

If you change to the Code:

all_h1.style("color","blue");

Three lines of text are displayed in blue.

What if I want to select the second h1? As mentioned in the previous section, there are two methods: either adding id to h1 or using function. For details, see the previous section.


Next, insert a new h1 in the body.

var new_h1 = body.append("h1");new_h1.text("Append new h1");
In this example, a new h1 tag is inserted into the body, and the newly inserted element is returned, and the text is set to Append new h1.

When deleting an element, use remove for the selected element, for example:

new_h1.remove();
This is the element selected from the new_h1 variable.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.