D3, nested appends, and data flow

You cannot add multiple child elements within one chained command. You will need to save the parent selection in a variable. This should do what you want:

var data = [{ "label": "chocolate", "text": "Chocolate Cookie", "img": "https://stackoverflow.com/questions/13203897/chocolate.jpg" },
        { "label": "sugar", "text": "Sugar Cookie", "img": "sugar.jpg" }];

var diventer = d3.select("body").selectAll("div")
    .data(data)
  .enter().append("div")
    .attr("id", function(d) { return d.label; });

diventer.append("p")
    .text(function(d) { return d.text; });

diventer.append("img")
    .attr("src", function(d) { return d.img; });​

See working fiddle: http://jsfiddle.net/UNjuP/

You were wondering how a child element like p or img, gets access to the data that is bound to its parent. The data is inherited automatically from the parent when you append a new element. This means that the p and img elements will have the same data bound to them as the parent div.

This data propagation is not unique for the append method. It happens with the following selection methods: append, insert, and select.

For example, for selection.append:

selection.append(name)

Appends a new element with the specified name as the last child of
each element in the current selection. Returns a new selection
containing the appended elements. Each new element inherits the data
of the current elements, if any, in the same manner as select for
subselections. The name must be specified as a constant, though in the
future we might allow appending of existing elements or a function to
generate the name dynamically.

Feel free to ask about the details if something is not clear.


EDIT

You can add multiple child elements without storing the selection in a variable by using the selection.each method. You can then also directly access the data from the parent:

var data = [{ "label": "chocolate", "text": "Chocolate Cookie", "img": "https://stackoverflow.com/questions/13203897/chocolate.jpg" },
        { "label": "sugar", "text": "Sugar Cookie", "img": "sugar.jpg" }];

d3.select("body").selectAll("div")
    .data(data)
  .enter().append("div")
    .attr("id", function(d) { return d.label; })
    .each(function(d) {
        d3.select(this).append("p")
          .text(d.text);
        d3.select(this).append("img")
          .attr("src", d.img);
    });

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)