Reputation: 9461
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 div
s? 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
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
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
Reputation: 324800
CSS! white-space
! pre-wrap
! Learn about it!
<div style="white-space: pre-wrap">
SPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACE!
Newlines totally work now!
</div>
Upvotes: 2
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