Making new stuff - Getting started with d3js part 2

Once we have a selection, we may want to create more elements under it. This is done using the selection.append(type) method.

So if we have the following code

<html>
  <head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
  </head>
  <body></body>
  <script>
    d3.select("body").append("div").text("hi");
  </script>
</html>

Example 2.1 - View on Plunker

We will end up with a single DIV in our body with the text "hi". One thing to be clear about here is the way that selection changes in a d3 statement.

d3.select("body") // We are now operating on the BODY element
.append("div")    // We are now operating on the new DIV element
.text("hi");      // Still the DIV, we change its text not the BODY

A larger example changes some other things
d3.select("body") // Selected the BODY 
  .append("div")  // Create the DIV and it is the selection
  .style("background-color","red") //Change the DIV style
  .append("span") // Append the SPAN inside the DIV and select
  .style("color","green") //Change the text color of the SPAN
  .text("hi");    // Change the text of the SPAN

Example 2.2 - View on Plunker

What if we want to create two items on the level inside the div? To do that we save the selection of the div in a variable and work off of that variable multiple times:

// Select the body and append a div, saving the div selection
// in the divSelection variable
var divSelection = d3.select("body").append("div");

// Use divSelection to act on the DIV multiple times
divSelection.style("background-color","red");

divSelection.append("span")
      .style("color","green")
      .text("hi");

divSelection.append("span")
      .style("color","blue")
      .text(" there!"); 

Example 2.3 - View on Plunker

Learning when to save a selection for later use comes in extremely handy as you move forward into D3. For example we could save the two spans for later use like this:

var divSelection = d3.select("body").append("div");
divSelection.style("background-color","red");

var spanSelection1 = divSelection.append("span")
            .style("color","green")
            .text("hi");

var spanSelection2 = divSelection.append("span")
            .style("color","blue")
            .text(" there!");

Example 2.4 - View on Plunker

Then later on we could go back and edit them individually if we so desired.



Comments