Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript add linebreak, \n not working

I want to add a linebreak in Javascript, but \n is not working and nothing else I found so far is not working (like <br> or \n). Also, because of the programming I cannot use .appendChild.

for (i=getchilds();i<number;i++){
     container.appendChild(document.createTextNode("\n" + "Pers. " + (i+1) + " \u00a0"));
     var input = document.createElement("input");
     input.type = "number";
     container.appendChild(input);
}
like image 446
Rob Avatar asked Oct 15 '25 16:10

Rob


1 Answers

I think you may be confusing whitespace with the representation of whitespace. In your case you're appending characters that represent white-space to a string that you intend to be displayed as a line-break. I assume you're then appending it to an element whose style is not set to display it as white-space.

There are four basic ways to fix this:

  1. Use an ordered list. If you can, do this, since it will be both structural and semantic. Notice the link shows how to control the list-item text (controlling the start number is more challenging).
  2. If the container-referenced element accommodates this, add white-space: pre to it's style. This will cause your line-breaks to come into view. It's best to do this with CSS, but you can do it with Javascript too.
  3. Replace the \n with a <br>. Denys Séguret has an example of this.
  4. Use a pre tag for the container-referenced element. <pre> automatically respects and displays line-breaks in content. This of course implies your content accommodates using a pre-formatted tag.
like image 192
Jared Farrish Avatar answered Oct 17 '25 07:10

Jared Farrish