What is the appropriate way to make a line break in Javascript

How can I make a line break in a proper way in Javascript?

I was going through the w3schools site for a solution and they came up with this:

<p id="demo"></p>

<script>
    document.getElementById("demo").innerHTML = "Hello \
Dolly.";
</script>

I tried this code in their Tryit Editor v2.1 provided in their site but this code doesn't work properly there. In the output, everything's ok, except there is actually no line break between the strings 'Hello' and 'Dolly'.

I've also checked this code in my Netbeans 8.0.1 ide and encountered the exact same problem here as well.

I have no idea where the problem is. Or is this not the right way to make a line break? If so, what is the right way to make a line break? Is there a better approach? Please help.

My browser is Mozilla Firefox ver. 32.0.3

Edit - 1:

Thanks a lot to users @ahmadalbayati, @webeno and @TheProvost for providing me the solution. It has been fixed. However, I'd like to add that, apart from their solution, the following code:

<script>
    document.write("Hello <br/> Dolly.");
</script>

gives me the exact same output as well. The same, just instead of manipulating a specific html element, it's writing something to the whole html.

Upvotes: 1

Views: 199

Answers (2)

benomatis
benomatis

Reputation: 5633

Purely going out from your example (doing this in html), the following should work:

document.getElementById("demo").innerHTML = "Hello <br /> Dolly.";
<p id="demo"></p>

EDIT: just mentioning @ahmadalbayati's name here who provided the answer first in a comment, though I have not seen that before posting this answer (probably didn't refresh the screen).

Upvotes: 3

TheProvost
TheProvost

Reputation: 1893

"\" allows you to have multiple lines that the browser can understand for the script. But it wont make a new line for the output. Do something like this to create a new line in the output.

<script>
    document.getElementById("demo").innerHTML = "Hello <br/> Dolly.";
</script>

Upvotes: 5

Related Questions