Roman
Roman

Reputation: 9461

\n is not creating a new line between text in javascript

I have a piece of JavaScript that is supposed to update a in my HTML:

var StringContent = ({
    "a": 'Some String a',
    "b": 'Some string b',
    "c": 'Some string c',
});

Then I want each string a, b, c displayed on a new line via:

document.getElementById("overlaycontent").innerHTML = (
    StringContent.a + '\n' +
    StringContent.b + '\n' +
    StringContent.c,
    )

All I get at the moment is everything in a single line. How do I create a new line in my text without adding more divs? I also tried \r, but that also does not help. I looked at the docs, but it keeps saying to use \n.

Upvotes: 0

Views: 360

Answers (4)

gtr1971
gtr1971

Reputation: 2732

\n (or sometimes \r\n) will work when outputting to a text element such as <textarea> or to a .txt document, but <br> is required for HTML.

Upvotes: 0

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

You should replace \n by <br> since innerHTML takes an HTML string (in HTML, \n merges with adjacent spaces but does not produce a carriage return except for elements with the style white-space:pre-wrap as noted by MaxArt) :

document.getElementById("overlaycontent").innerHTML = (
    StringContent.a + '<br>' +
    StringContent.b + '<br>' +
    StringContent.c,
)

Upvotes: 5

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324800

CSS! white-space! pre-wrap! Learn about it!

<div style="white-space: pre-wrap">




                       SPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACE!

Newlines totally work now!
</div>

Upvotes: 2

Mimouni
Mimouni

Reputation: 3630

for innerHTML you need '<br />'

document.getElementById("overlaycontent").innerHTML = (
    StringContent.a + '<br />' +
    StringContent.b + '<br />' +
    StringContent.c
    )

but for an alert you can use : String.fromCharCode(10) instead of '\n'

alert(
    StringContent.a + String.fromCharCode(10) +
    StringContent.b + String.fromCharCode(10) +
    StringContent.c
    )

Upvotes: 1

Related Questions