简体   繁体   中英

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

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 d3 ish 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.

you should appendChild to the div;

try something like this(this is 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM