Skip to content

Instantly share code, notes, and snippets.

@phoebebright
Created November 5, 2012 16:35
Show Gist options
  • Save phoebebright/4018151 to your computer and use it in GitHub Desktop.
Save phoebebright/4018151 to your computer and use it in GitHub Desktop.
D3 to nest or not to nest selections - examples
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment