Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join existing elements of the DOM to data with d3.js

Tags:

d3.js

I'm trying to join existing input text (selected by d3.selectAll()) that have unique id's corresponding to keys in the data joined with D3. I would like D3 to associate the ids of the input elements to the keys of the data, but it doesn't.

Association is done in the order in witch they appear in the DOM and in the array respectively.

Is there a way to do this ?

like image 916
Fabrizio Avatar asked Jan 03 '13 23:01

Fabrizio


1 Answers

Remember that the key function will be invoked on each element of your data array (i.e. dt), as well as on each element in your selection (i.e. d3.selectAll(".input")). In both cases, the key function needs to return a valid value and those output values will used to make the association.

To achieve your goal you can do something like the following example. See fiddle for live version: http://jsfiddle.net/2Fkjq/

If your document contains the following:

<div id="c"></div>
<div id="a"></div>
<div id="b"></div>

​ then executing this:

var data = [
    { key: "a", val: "aaa" },
    { key: "b", val: "bbb" },
    { key: "c", val: "ccc" }
];

d3.selectAll("div")
    .data(data, function(d) { return (d && d.key) || d3.select(this).attr("id"); })
    .text(function(d) { return d.val; });

will result in this document:

<div id="c">ccc</div>
<div id="a">aaa</div>
<div id="b">bbb</div>

You see that the key function consists of two parts. The first part is designed for the data array:

(d && d.key)

That part will return undefined for the elements in the d3 selection. The second part targets those elements:

d3.select(this).attr("id")
like image 71
nautat Avatar answered Sep 18 '22 11:09

nautat