Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type new line character in Element.TextContent

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.

First attempt

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 &nbsp) is there.

Trying <br/>.

If I try to use <br/>, I must use innerHTML:

var el = document.getElementById("myel");
var newline = "<br/>";
var nbsp = "&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.

like image 770
Andry Avatar asked Jun 23 '15 12:06

Andry


People also ask

How do I add a new line in HTML?

<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.

How do you make a new line in CSS?

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.

How do you add a new line in JavaScript?

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.


1 Answers

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>
like image 142
Rick Hitchcock Avatar answered Oct 10 '22 23:10

Rick Hitchcock