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:
\n
work?<br>
even work? Shouldn’t everything that’s inside the script tags be strictly JavaScript instead of a dirty mix between HTML and JS?\n
work somehow?\t
doesn’t work either. Any other stuff that won’t work inside HTML files?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
.
\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.