Skip to content

Instantly share code, notes, and snippets.

@tsenga
Created December 4, 2012 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsenga/4199266 to your computer and use it in GitHub Desktop.
Save tsenga/4199266 to your computer and use it in GitHub Desktop.
Visualisation Exploration: D3: Parent data query

Intriguing question from stackoverflow:

http://stackoverflow.com/questions/13662756/d3-js-passing-data-from-parent-to-child-nodes

This solution feels a little messy, since it goes into the dark details of d3.js - I'm only partially comforted by the fact that Mike Bostock's documentation, refers directly to use of __data__ and selection[0][0].

It also makes use of the 3rd function parameter, most usage of the data access function uses either 1 parameter (the data element) or 2 parameters (data element + index). But there is a 3rd parameter, through which d3 passes the current selection group index.

This 3rd function parameter - I recall reading about, but can't find the source. I would welcome being pointed at source material that documents its use!

<html>
<head>
<title>D3 ParentNode Query</title>
<script src="http://d3js.org/d3.v2.min.js"></script>
</head>
<body>
<h1>Vis Exploration - D3 - ParentNode Query</h1>
<div id="chart"></svg>
</body>
<script type="text/javascript">
var data = [{
key : 'likes', values : [
{key : 'blue-frog', value : 1},
{key : 'goodbye', value : 2}
]
}, {
key : 'dislikes', values : [
{key : 'blue-frog', value : 3},
{key : 'goodbye', value : 4 }
]
}, {
key : 'noopinion', values : [
{ key : 'blue-frog', value : 5},
{ key : 'stars', value : 6 }
]
}];
var root = d3.select("#chart");
var firstLevel = root.selectAll("ul")
.data(data)
.enter()
.append("ul")
.attr("class", function(d) { return d.key; });
// secondLevel is an array of selections, grouped by the different elements from firstLevel
var secondLevel = firstLevel.selectAll("li")
.data(function(d) { return d.values; })
.enter();
secondLevel
.append("li")
.text(function(d,i,j) { // can take a 3rd parameter - which specifies the selection group
// traverse to parentNode (HTML) via .parentNode
// traverse to our bound data via __data__
return secondLevel[j].parentNode.__data__.key + " ... " + d.key + " - " + d.value;
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment