1

The embedded "\n" characters in the following code does NOT produce line breaks in the generated string. What am I to do??? :-)

/* Load array into DOM */
var directory = document.getElementById ("directory");
directory.innerHTML = "";
var numberOfHouses = house.length;
for (i = 0; i < numberOfHouses; i++) {
    var houseNode = document.createElement('span');
    var text = (house[i][0] + "\n" + house[i][1] + "\n" + house[i][2] + "\n" + house[i][3] + "\n " + house[i][4] + "\n" + house[i][5] + "\n" + house[i][6] + "\n" + house[i][7] + "\n" + house[i][8] + "\n\n");
    var houseText = document.createTextNode(text);
    houseNode.appendChild(houseText);
    directory.appendChild(houseNode);       
  }
javac
  • 2,431
  • 4
  • 17
  • 26
  • The string data outputs, but not with embedded line breaks. – Jerald Dana Cole May 13 '15 at 18:08
  • 1
    Duplicate of http://stackoverflow.com/questions/1155678/javascript-string-newline-character. If you are ultimately writing the string to html you can use the br tag to create line breaks. Remember that HTML collapses whitespace including line breaks by default. – Ryan May 13 '15 at 18:19

3 Answers3

1

That's because a linefeed in a text node does not render as a linefeed.

If you want a linefeed on a web page, you need to use CSS such as white-space: pre-line; to make them count, or add a <br> element

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
0

You need to be using <br> to make the new lines. You are creating the string in javascript, but it is being interpreted in HTML.

kaz
  • 1,190
  • 8
  • 19
0
var directory = document.getElementById ("directory");
directory.innerHTML = "";
var numberOfHouses = house.length;
for (row = 0; row < numberOfHouses; row++) {
  var houseNode = document.createElement('span');
  for (column = 0; column < 9; column++) {
    var text = (house[row][column]);
    var houseText = document.createTextNode(text);
    houseNode.appendChild(houseText);
    directory.appendChild(houseNode);
    var brNode = document.createElement ('br');
    houseNode.appendChild(brNode);
  }
  var pNode = document.createElement('p');
  directory.appendChild(pNode);
}

// Fixed!