user663724
user663724

Reputation:

How to Write HTML in javascript with new line (\n) option

I have large HTML to be generated dynamically through javascript so the reason i dont want it be in a single line

I was trying it as this way but getting Uncaught SyntaxError: Unexpected token ILLEGAL under browser console

for(var i=0;i<response.length;i++)
{
    divhtml.append('<li>
        <h6>'+response[i].RestaurantName+'</h6>\n
        <p>'+response[i].Locality+'</p>\n
        </li>');
}

Please see this fiddle

http://jsfiddle.net/eb1t5jop/3/

Upvotes: 0

Views: 36

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

You put a backslash at the end of the line just before the newline:

for(var i=0;i<response.length;i++)
{
    divhtml.append('<li>\
        <h6>'+response[i].RestaurantName+'</h6>\
        <p>'+response[i].Locality+'</p>\
        </li>');
}

This is covered in §7.8.4 - String Literals in the spec (see LineContinuation).

Note that:

  • The escaped newline will not be in the string; if you want a newline (unnecessary in HTML where you have those \ns), include a \n prior to the \ at the end of the line.

  • Leading spaces on subsequent lines will be in the string

Upvotes: 1

Related Questions