Shawn
Shawn

Reputation: 132

How to programatically add line break to a paragraph tag

I want to apply a line break to a dom element programatically.

I have tried to used <br>, <br/> and \n from different answers of solving this problem.

However, none of them work.

Here is an example:

document.getElementById('1').textContent = "\n".repeat(6)
document.getElementById('2').textContent = "<br/>".repeat(6)
p {
  border: 1px solid black;
}
<h2>Set <code>\n</code></h2>
<p id="1"></p>

<h2>Set <code>&lt;br/&gt;</code></h2>
<p id="2"></p>

The <br>, <br/> will appear in the textContent, but doesn't apply the line break.

The \n doesn't appear in the textContent, and also doesn't apply the line break.

Do anyone know how to solve this problem?

Upvotes: 0

Views: 1372

Answers (1)

KyleMit
KyleMit

Reputation: 29927

Encoding

Whitespace

\n will add a new line, but since html is whitepsace agnostic, it won't show up by default inside of a <p> tag. If you want to add line breaks, you can use <br/> instead

Demo in Stack Snippets

document.getElementById('1').textContent = "<br/>".repeat(6)
document.getElementById('2').innerHTML = "<br/>".repeat(6)
p {
  border: 1px solid black;
}
<h2>Set <code>textContent</code></h2>
<p id="1"></p>

<h2>Set <code>innerHTML</code></h2>
<p id="2"></p>

Upvotes: 2

Related Questions