user2846569 user2846569 - 1 month ago 14
Javascript Question

d3 append whitespace after appended div

I have following code:

this.other.selectAll('div').data(this.words).call(function(){
this.enter().append('div').each(function() {
...


This creates a structure where divs are along each other, like

<div></div><div></div>


But I want them space separated

<div></div> <div></div>


to work with (for container)

text-align: justify;


I have for divs

display: inline-block;


How to insert these spaces nicely?




So far I have a solution with jquery, but I am really interested to know how to do it in d3

Answer

Using .each you can tap into the list of elements and simply add a space before each span:

this.other.selectAll('div').data(this.words).call(function(){
  this.enter().append('div').each(function() {
    if (this.previousSibling && previousSibling.nodeValue == ' ') {
      return;  // Already have a space before this span, don't add another.
    }

    this.insertAdjacentHTML('beforebegin', ' ')
  });
...

Another option is to use the ::after pseudo-element and a non-breaking space character:

div {
  display: inline-block;
}
div::after {
  content: '\00a0';  // Non-breaking space.
}