Skip to content Skip to sidebar Skip to footer

How To Create Multiple Adjacent Nodes Per Data Element With D3.js Selections

With data like: var days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat']; I need to have the html structure become:
&

Solution 1:

You're getting this structure because D3 does a batch processing of sorts with the selections. That is, each operation you perform on a selection is performed on all the elements at once.

In your case, you probably want to use .each(), which allows you to call a function on each element of the selection. The code would look something like this.

var enter    = selection.selectAll("input").data(days).enter();
enter.each(function() {
  selection.append("input");
  selection.append("label");
});

This won't work, as pointed out by @Holger because the .enter() selection doesn't define .each(). The way below will work though.

A better solution in your case would be to encapsulate the elements you want to appear together in another div though. This would allow you to use D3 in a more standard way. The code would look like this.

var enter    = selection.selectAll("input").data(days).enter();
var divs = enter().append("div");
divs.append("input");
divs.append("label");

Post a Comment for "How To Create Multiple Adjacent Nodes Per Data Element With D3.js Selections"