I am trying to create a definition list such as this one:
<dl>
<dt>term1</dt>
<dd>definition1</dd>
<dt>term2</dt>
<dd>definition2</dd>
<dt>term3</dt>
<dd>definition3</dd>
</dl>
by using a JSON in this form:
{
"term1":"definition1"
"term1":"definition2"
"term3":"definition3"
}
. Whch is the most elegant way to do it with d3.js?
PS: I would like to use the <dl>
element because it seems the most appropriate way to semantically represent a key:value pair:
Here is what I would do:
JsFiddle: http://jsfiddle.net/chrisJamesC/RZdQw/
Then, if you want to be more d3 specific, you can use selections (more about implementation).
By the way, using arrays might be easier than json objects to represent lists
When the content is simple like you describe, the easiest way may be to just directly create paired HTML elements and bind the data to them afterward.
Also everything is much easier as a list -- D3's entries function can easily blow your object out to a list of objects:
JsFiddle: http://jsfiddle.net/slushy/bbh6a4w0/
Solution for d3 v3.x; no longer works as of d3 4.0
I struggled with the same issue for a while. What I found was the behavior of insert() with the enter() selection does the trick. This is based on the interaction between the enter selection whose inserted or appended elements are merged into the update selection, the the way that insert works with enter selections. The relevant bits in the documentation:
The result is that if you insert some dt elements into the enter selection, they will be merged into the update selection. Then, if you then insert some dd elements into the enter selection, they will be "inserted immediately before the next following sibling in the update selection"; that is, they'll be right after their associated dt.