Why doesn’t JavaScript newlines work inside HTML?

user723636 picture user723636 · Apr 25, 2011 · Viewed 25.9k times · Source

I have the following:

<html>
  <body>
    <script type="text/javascript">
      document.write('Hello\nWorld')
    </script>
  </body>
</html>

As you probably all know, \n doesn’t work and I have to use <br> instead. It won’t work either if I link to an external .js file. Here are my questions:

  1. Why doesn’t \n work?
  2. Why does <br> even work? Shouldn’t everything that’s inside the script tags be strictly JavaScript instead of a dirty mix between HTML and JS?
  3. Is it possible to make \n work somehow?
  4. I know \t doesn’t work either. Any other stuff that won’t work inside HTML files?
  5. Unrelated question (I didn’t want to open a new question just for this): I installed Node.js to be able to try out JS scripts from inside vim but when I run this script I get the error "document is not defined". Same thing happens when I try from the REPL. Any ideas?

When searching for similar questions, all I got was that I should use <br> instead of \n.

Answer

Quentin picture Quentin · Apr 25, 2011

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.