How to add text to div in D3

All:

For example, I have a string array:

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

      

I want to add all of them to a div with separating them:

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

      

Wondering how to do this with D3? I think using selectAll () ... data () ... enter (). Append (), but I don't know how to add that.

thank

+3


source to share


2 answers


Data binding in d3

roughly adds an element to the dom for every element in your data. However, you are asking how to get one element with my strings separated <br/>

:

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

      

More d3

ish way to get the same look and feel (but this gives you a div per line):

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

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

      



The 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.

+4


source


you should add appendChild to the div;

try something like this (it's pure js !!!):



var myArray=["string1","string2","string3","string4","string5"];
var test = document.querySelector(".test")
myArray.forEach(function(x){
var textnode = document.createTextNode(x);
test.appendChild(textnode )
}) 

      

https://jsfiddle.net/maio/m3sqjjb3/

+2


source







All Articles