Jerald Dana Cole
Jerald Dana Cole

Reputation: 21

Embedding a new line character in a JavaScript string

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);       
  }

Upvotes: 1

Views: 235

Answers (3)

Jerald Dana Cole
Jerald Dana Cole

Reputation: 21

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!

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65116

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

Upvotes: 1

kaz
kaz

Reputation: 1190

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.

Upvotes: 0

Related Questions