Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.writeln doesn't write to a new line

Tags:

javascript

I was just writing some simple code and I noticed that using document.writeln doesn't write to a new line, permit me to demonstrate...

    // this is my JSON object
var myObject = {
 "firstName": "John",
 "lastName": "Smith",
 "age": 25,
 "address": [{
    "Address1": "11 My Street",
    "Address2" : "Nice Area",
    "Town" : "Nice Town",
    "PCode" : "P05T 0DE"
    }]
 }

document.writeln(myObject.firstName);
document.writeln(myObject.address[0].Address1);

now this outputs the following....

John 11 My Street

It's all on one line? If I used document.write() I'd expect this? It's happening in both IE & Firefox. Obviously I could add + "<br/>" or + "\n" but I shouldn't need to do that?

Am I being stupid?

like image 640
Mark Sandman Avatar asked Apr 26 '11 20:04

Mark Sandman


People also ask

How do you insert a new line in a document?

Use the \n for a newline character. document. write("\n");

What is the difference between document write and document writeln?

The Difference Between write() and writeln()writeln() adds a newline character after each statement. write() does not.

How do you break a line in script tag?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.

How do you write a BR tag in a document?

The <br> tag inserts a single line break. The <br> tag is useful for writing addresses or poems. The <br> tag is an empty tag which means that it has no end tag.


2 Answers

view the source of the page to see how the browser puts each line on a line- but if you want to see a newline in the html, yes, put a '<br>' between them.

like image 153
kennebec Avatar answered Oct 22 '22 12:10

kennebec


document.writeln does this:

Writes a string of text followed by a newline character to a document.

But whitespace is collapsed and converted to a single space when rendering HTML so your newline does nothing inside the HTML.

like image 25
mu is too short Avatar answered Oct 22 '22 10:10

mu is too short