Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending multiple non-nested elements for each data member with D3.js

I would like to create multiple non-nested elements using d3 to create a structure like this:

    <div id="parent">         <p> from data[0] </p>         <p> from data[0] </p>          <p> from data[1] </p>         <p> from data[1] </p>          <p> from data[2] </p>         <p> from data[2] </p>     </div> 

creating nested structures would go something like

    d3.select('#parent').selectAll('p').data(data).enter().            append('p')...append('p') 

but I would like to maintain the original selection even after the append, so I could continue appending to the parent element. Thank you!

like image 754
user4815162342 Avatar asked Jan 31 '14 17:01

user4815162342


People also ask

What is D3 js explain select () selectAll () and data () in brief?

select() − Selects only one DOM element by matching the given CSS selector. If there are more than one elements for the given CSS selector, it selects the first one only. selectAll() − Selects all DOM elements by matching the given CSS selector. If you are familiar with selecting elements with jQuery, D3.

What does selectAll do in D3?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.

What does D3 append do?

append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element. If the type that is given is a function then it must be evaluated for each element that is in the selection.


1 Answers

The idomatic way of doing is with nesting:

var divs = d3.select('#parent').selectAll('p').data(data).enter().append('div');  divs.append('p') divs.append('p') 

Which creates:

<div id="parent">   <div>     <p> from data[0] </p>     <p> from data[0] </p>   </div>    <div>     <p> from data[1] </p>     <p> from data[1] </p>   </div>    <div>     <p> from data[2] </p>     <p> from data[2] </p>   </div> </div> 

If that won't work, save your selection and repeatedly append:

var enterSelection = d3.select('#parent').selectAll('p').data(data).enter();  enterSelection.append('p') enterSelection.append('p') 

then sort what you've added:

d3.select('#parent').selectAll('p').sort(function(a, b){ return a.index - b.index; }) 

You'll need to add an index property to each element of data that describes the sort order. The normal i is only defined in the context of a particular selection, which is lost when we reselect.

like image 194
Adam Pearce Avatar answered Sep 21 '22 20:09

Adam Pearce