1

I am learning table in D3, my question is when to use ".select()":

For instance, when building circles:

var circles = svg.selectAll("circle")
    .data(dataSet)
    .enter()
    .append("circle")
    .attr("r", 2.5)
    .attr("cx", function(d){ return d.x})
    .attr("cy", function(d){ return d.y});

select circle (empty)-> append circle

but when I am building a table,

The following code directly appends the table, without select("table") first. Same for the "tr".

function tabulate(data, columns) {
    var table = d3.select("#container").append("table"),
        thead = table.append("thead"),
        tbody = table.append("tbody");

    // append the header row
    thead.append("tr")
        .selectAll("th")
        .data(columns)
        .enter()
        .append("th")
            .text(function(column) { return column; });

(code from "creating a table from csv")

Why won't the following code works?

function tabulate(data, columns) {
    var table = d3.select("#container")
        .select("table")
        .append("table"),
        thead = table.append("thead"),
        tbody = table.append("tbody");

thanks in advance,

Community
  • 1
  • 1
muyueh
  • 1,018
  • 13
  • 16

1 Answers1

0

Select is generally used when you already know that a specific element exists, and you want to get a reference to it and make changes (or append children) to it. Since you know that there is no table tag in the div, there's no point in selecting it.

If you didn't know for sure if the table tag existed and you wanted to create it based on some other data, you could modify your code to look something like this:

var table = d3.select("#container")
    .select("table")
    .data(['hi'])
    .enter()
    .append("table"),
    thead = table.append("thead"),
    tbody = table.append("tbody");

HOWEVER, there's a subtle difference in how select and selectAll work, as explained by the author in this answer. My example code creates the table tag directly inside the body rather than inside the div. Thus it's better to directly append unless you're really binding the element to data.

Community
  • 1
  • 1
explunit
  • 18,967
  • 6
  • 69
  • 94