The fact that your line shows without the \n
s in it is evidence that you are actually inserting new lines and not literal \
s and n
s. Therefore, your code is doing what you expect.
As others have pointed out, the problem here isn't the JavaScript code itself, but the HTML. When you're setting innerHTML
, you aren't setting text as if it were literal, but as part of the page's live HTML.
HTML is a markup language, and as such, it doesn't render exactly as it is written, but as the markup dictates. In HTML, whitespace is considered to be syntactically insignificant, as is the case with JavaScript and many other languages. That means that any whitespace, whether horizontal (such as spaces and tabs) or even vertical (such as newlines) are all replaced by a single space. Therefore, your newlines are replaced with spaces.
The proper way to force a new line in HTML is with the <br />
tag, which inserts a line break. However, best practices say that HTML is more about marking up data with context rather than style. There is probably a reason that you want these entries on lines by themselves. They are likely unique entries, and as such, they should probably be inside of their own "block level" elements. One popular example would be the <p></p>
tags that create paragraphs. Another example would be to use <li></li>
for list items, as such:
<body>
<button onclick="myFunction()">Click me</button>
<div id="demo" onclick="myFunction()"></div>
<script>
function myFunction() {
var list = document.createElement("ul");
list.style.listStyleType = "none";
for (var i=1; i <= 6; i++) {
var item = document.createElement("li");
item.appendChild(document.createTextNode("line" + i));
list.appendChild(item);
}
document.getElementById("demo").appendChild(list);
}
</script>
</body>
Ideally, the styling would be done in CSS, but this shows the idea. This would be a more robust approach to adding the elements which will form the new lines.
` – Jun 12 '17 at 13:59
``` tag here => https://developer.mozilla.org/en/docs/Web/HTML/Element/br – kkaosninja Jun 12 '17 at 14:00