Why doesn’t JavaScript newlines work inside HTML?

Why doesn’t \n work?

Because white space is just white space in HTML.

Why does <br> even work?

Because it is the HTML for a line break

Shouldn’t everything that’s inside the script tags be strictly JavaScript instead of a dirty mix between HTML and JS?

That’s subjective. document.write is considered dirty by many as well.

You can always use createElement and createTextNode

Is it possible to make \n work somehow?

<pre>, white-space

I know \t doesn’t work either. Any other stuff that won’t work inside HTML files?

HTML is not plain text. Listing all the differences would be time-consuming, and out of scope for Stack Overflow. Try reading the specification.

Unrelated question (I didn’t want to open a new question just for this)

It is completely unrelated. Open a new question.


I had:

<div>Hello\nworld</div>

I added the below css to div class and it's working now:

div {
      white-space: pre-wrap;
  }

I hope this solve your problem too.


\n works. If you have a debugger of sorts (or similar developer tool), you can see the document source, and you will see that there is indeed a newline character. The problem is the way you are looking at the page: you’re not reading its source, you’re reading it as an HTML document. Whitespace in HTML is collapsed into a single space. So when you change the source, it does indeed change, although when interpreted as an HTML document, that change isn’t shown.

Your Node.js error is most probably caused by the fact that you’re running browser scripts on the server. I.e. scripts that refer to the document are intended to be run in a browser, where there is a DOM etc. Although a generic node process doesn’t have such a global object because it isn’t a browser. As such, when you try and run code that references a global object called document on the assumption that it exists just like in the browser, it will throw an error. document.write doesn’t exist; if you want to write to the screen, try console.log or look into the other util functions.


When HTML renders, it ignores whitespace. Thus the only way is to use line breaks.

Use <br/> instead of \n and it will work fine

The document.write() function writes HTML into the element.


When you write to the page, you're not writing JavaScript; you're writing HTML. \n is a special "line feed" character that doesn't create a line break in the browser's rendering of the HTML. It WILL create a line break in the HTML file itself, but the browser doesn't take this into consideration when it renders out the markup.

Thus, the br tag is required.