Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append text to a div in D3

All:

For example I have array of string:

["string1","string2","string3","string4","string5"]

I want to add all of them into a div with
separate them like:

<div>
string1<br>
string2<br>
string3<br>
string4<br>
string5
</div>

I wonder how to do it with D3? I am thinking use selectAll()...data()...enter().append(), but I do not know how to append this.

Thanks

like image 694
Kuan Avatar asked May 28 '15 23:05

Kuan


1 Answers

Data binding in d3 is about appending an element to the dom for each item in your data. What you are asking for, though, is how do I get one element with my strings separated by a <br/>:

  var arr = ["string1","string2","string3","string4","string5"];
  d3.select('body')
    .append('div')
    .html(arr.join('<br/>'));

A more d3ish way to get the same appearance is (but this gives you a div per string):

  var arr = ["string1","string2","string3","string4","string5"];

  d3.select('body')
    .selectAll('div')
    .data(arr)
    .enter()
    .append('div')
    .text(function(d){
      return d;
    });

A third approach is to use <span>s:

d3.select('body')
    .selectAll('span')
    .data(arr)
    .enter()
    .append('span')
    .text(function(d){
      return d;
    })
    .append('br');

Here's an example with both approaches.

like image 168
Mark Avatar answered Oct 22 '22 10:10

Mark