Attach existing DOM elements to data using d3.js

I am trying to join an existing input (selected by d3.selectAll() ) that has a unique identifier corresponding to the keys in the data connected to D3. I would like D3 to bind input element IDs with data keys, but that is not the case.

Association is performed in the order specified in the DOM and in the array, respectively.

Is there any way to do this?

+4
source share
1 answer

Remember that a key function will be called for each element of your data array (ie dt), as well as for each element of your choice (ie d3.selectAll (". Input")). In both cases, the key function must return a valid value, and these output values ​​will be used to create the association.

To achieve your goal, you can do something like the following example. See the script for the 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 do the following:

 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 lead to 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 for the data array:

 (d && d.key) 

This part will return undefined for items in d3 selection. The second part is for these elements:

 d3.select(this).attr("id") 
+7
source

Source: https://habr.com/ru/post/1209587/


All Articles