I want to apply line break in a loop in javascript.
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:
let arr = [1,2,3,4,5,6]
let result = document.querySelector('p')
for(let i = 0;i<arr.length;i++){
result.textContent += arr[i]+"<br>"
result.textContent += arr[i]+"<br/>"
result.textContent += arr[i]+"\n"
}
<p></p>
The <br>
, <br/>
will appear in the textContent
and doesn’t apply the line break.
The \n
doesn’t appear in the textContent
, but doesn’t apply the line break.
Do anyone know how to solve this problem?
Thanks for any responds.
>Solution :
Encoding
textContent
will escape the values you pass.innerHTML
will perserve the string as html
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>