Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>var data = [{ "label": "chocolate", "text": "Chocolate Cookie", "img": "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; });​ </code></pre> <p>See working fiddle: <a href="http://jsfiddle.net/UNjuP/">http://jsfiddle.net/UNjuP/</a></p> <p>You were wondering how a child element like <code>p</code> or <code>img</code>, 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.</p> <p>This data propagation is not unique for the <code>append</code> method. It happens with the following <code>selection</code> methods: <a href="https://github.com/mbostock/d3/wiki/Selections#wiki-append"><code>append</code></a>, <a href="https://github.com/mbostock/d3/wiki/Selections#wiki-insert"><code>insert</code></a>, and <a href="https://github.com/mbostock/d3/wiki/Selections#wiki-select"><code>select</code></a>.</p> <p>For example, for selection.append:</p> <blockquote> <h1>selection.append(name)</h1> <p>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.</p> </blockquote> <p>Feel free to ask about the details if something is not clear.</p> <hr> <p>EDIT</p> <p>You can add multiple child elements without storing the selection in a variable by using the <code>selection.each</code> method. You can then also directly access the data from the parent:</p> <pre><code>var data = [{ "label": "chocolate", "text": "Chocolate Cookie", "img": "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); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload