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);       
  }
2
  • The string data outputs, but not with embedded line breaks. Commented May 13, 2015 at 18:08
  • 1
    Duplicate of stackoverflow.com/questions/1155678/…. 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. Commented May 13, 2015 at 18:19

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.