简体   繁体   中英

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.

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.

textContent will escape the values you pass - you should set innerHTML instead

 document.getElementById('1').textContent = "<br/>\n".repeat(6) document.getElementById('2').innerHTML = "<br/>\n".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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM