public
Last active

D3 to nest or not to nest selections - examples

  • Download Gist
index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
<!DOCTYPE html>
<html>
<head>
<title>Map</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
.one {
background: #a7eea4;
}
.two {
background: #6cbeee;
 
}
div {
margin: 3px;
}
</style>
</head>
<body>
<!--<h1 id='calendar_view'>Calendar View</h1>-->
<code> var data = [['apples','red'], ["oranges", "orange"], ["bananas", "yellow"]];
</code>
 
<h3>List all first entries in array then all second ones </h3>
<div id='chain'> </div>
<h3>Second element is nested inside first element</h3>
<div id='nested'> </div>
<h3>Both elements are contained in a third element</h3>
<div id='append'> </div>
 
<p>Documentation: <a href="http://bost.ocks.org/mike/nest/">http://bost.ocks.org/mike/nest/</a></p>
<script type="text/javascript">
 
var data = [['apples','red'], ["oranges", "orange"], ["bananas", "yellow"]];
 
var anchor = d3.select("#chain");
 
var div1 = anchor.selectAll("#chain div")
.data(data);
 
div1
.enter().append("div")
.attr("class","one")
.text(function(d) { return d[0];});
 
div1
.enter().append("div")
.attr("class","two")
.text(function(d) { return d[1];});
 
 
anchor = d3.select("#nested");
 
var div2 = anchor.selectAll("#nested div")
.data(data);
 
div2
.enter().append("div")
.attr("class","one")
.text(function(d) { return d[0];});
 
div2
.append("div") // <--------- removed enter() here
.attr("class","two")
.text(function(d) { return d[1];});
 
 
anchor = d3.select("#append");
 
var div3 = anchor.selectAll("#append div")
.data(data)
.enter().append("div")
.attr("class","row");
 
div3.each(function(d) { // <-- each is the magic - requires an outer div
 
d3.select(this).append("div")
.attr("class","one")
.text(function(d) { return d[0];});
 
d3.select(this).append("div")
.attr("class","two")
.text(function(d) { return d[1];});
});
 
</script>
 
</body>
</html>
readme.mkd
Markdown

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.