9

I need to append a lot of HTML code. To improve readability, I don't want to write that all in one line, but split them as regular HTML. That would be like 15 new-lines or something. The problem is that JavaScript doesn't allow me to do that.

var target = $('.post .comment_this[rel="' + comment_id + '"]').parent().parent();

target.append('
    <div class="replies">
        <p>...</p>
        <img src="" alt="" />
    </div>
');

Basically, I need to add HTML in that place.

I need to add some variables too.

daGrevis
  • 21,014
  • 37
  • 100
  • 139

6 Answers6

11
    target.append(' <div class="replies">'+
            '<p>...</p>'+
            '<img src="" alt="" />'+
        '</div>'
    );

or

    target.append(' <div class="replies">\
            <p>...</p>\
            <img src="" alt="" />\
        </div>'
    );
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
2

Creating multiline strings in JavaScript

Community
  • 1
  • 1
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
  • I wrap each new line into `'quotes'` and added `+` before them. It works and looks a little bit better then when it was all in one line. – daGrevis Jul 01 '11 at 09:25
1
target.append(' ?>
    <div class="replies">
        <p>...</p>
        <img src="" alt="" />
    </div>
<?');

Separate the html and php with the close/open php tags and it should work fine.. when adding var's in the html, just use the tags again, like this: <? $hello ?>

Patrick R
  • 1,949
  • 3
  • 32
  • 58
0

As of 2015, ECMA 6, you can do this:

target.append(`
    <div class="replies">
        <p>...</p>
        <img src="" alt="" />
    </div>
`);
Jonathan
  • 6,741
  • 7
  • 52
  • 69
0

If you want to insert variables to html, you can use some templating library like jQuery.template

MarrLiss
  • 808
  • 5
  • 10
-1

use html() instead of append

target.html('<div class="replies"><p>...</p><img src="" alt="" />,</div>');
user555600
  • 164
  • 1
  • 4
  • 11