I am trying to generate a textual content in a web application. I want a text to appear into a header element <h1>
but the text must contain newline breaks.
var el = document.getElementById("myel");
var newline = "\r\n";
var nbsp = "\u00a0";
el.textContent = "My awesome" + newline + "web" + nbsp + "application";
This is not working. I mean in the developer tools, by inspecting the DOM, I can see the text being broken between "awesome"
and "web"
, but the browser does not render it that way: the text is all on the same line but at least the non breaing space (which is correctly rendered like  
) is there.
<br/>
.If I try to use <br/>
, I must use innerHTML
:
var el = document.getElementById("myel");
var newline = "<br/>";
var nbsp = " ";
el.innerHTML = "My awesome" + newline + "web" + nbsp + "application";
So there is no way I can get my problem solved by using textContent
? I would really like avoiding innerHTML
.
<br>: The Line Break element. The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.
The white-space property is used to insert the line break before an element. This property controls the text wrapping and white-spacing. Line break between the lines: The line break can be added between the line of text. The white-space: preline; is used to insert line break before an element.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
Use CSS white-space: pre;
with "\r\n"
:
var el = document.getElementById("myel");
var newline = "\r\n";
var nbsp = "\u00a0";
el.textContent = "My awesome" + newline + "web" + nbsp + "application";
#myel {
white-space: pre;
}
<h1 id="myel"></h1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With