Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply line break in a loop in js

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading