33

Im trying to append a large block of text using jquery's append().

$('#add_contact_btn').click(function(event) {
    event.preventDefault();

    var large = '<div class="accordian_container"><a href="#" class="accordian_trigger"><h4>Co-Borrower Information</h4></a><hr/><div class="accordian_item" id="accord_item_2"><label> First Name</label><br/><input type="text"/><br/><label>Middle Name</label><br/>
            <input type="text"/><br/>
            <label>Last Name</label><br/>
            <input type="text" /><br/>
            <label>Home Number</label><br/>
            <input type="text"/><br>
            <label>Work Number</label><br/>
            <input type="text"/><br>
            <label>Cell Number</label><br/>
            <input type="text"/><br>
            </div>
            </div>';

    $('#accordion_container').append(large);



});

It doesn't seem to be working and after looking at the documentation for append(), I can't figure out why - any ideas? Is it the large amount of HTML that I am trying to append?

Thomas
  • 5,030
  • 20
  • 67
  • 100

12 Answers12

46

Modern Answer

As ES6 (and beyond) becomes more common, and as more and more people transpile from ES6, we are more and more able to use template literals, which can be used as multiline strings:

var myString = `<p>Line One</p>
<p>Line Two</p>
<p>Line Three</p>`;

Original 2012 Answer (ES5)

Javascript does not have multiline strings in the way you are writing them, you can't just open a string on one line, go down a few lines and then close it. (there are some ways of doing multi-line strings in JS, but they are kind of backwards).

How most people do it is something like this:

var myString = '<p>Line One</p>' +
'<p>Line Two</p>' +
'<p>Line Three</p>';
Jimbo Jonny
  • 3,549
  • 1
  • 19
  • 23
  • If text has single quote(') ex ` Mr./Ms `, grunt build will fail, Please use below answer. It worked for me. – Ramesh Papaganti Aug 29 '17 at 11:15
  • 1
    @RameshPapaganti - That's true of any string, no matter what. If you use the character meant to close the string within the string (without escaping it, which can be done `'it\'s'` with a backslash)...then it's gonna think you're closing the string. JS is pretty good, but it's not telepathic :) – Jimbo Jonny Apr 15 '18 at 17:22
39

You could create a template in HTML that is hidden, then append its content HTML. For example:

<div class="hide" id="template">
  <b>Some HTML</b>
</div>

jQuery:

$("#container").append($("#template").html());

Putting HTML in a JavaScript string is harder to read and search for, is error prone and your IDE will struggle to format it properly.


Update 2019

Check out the template tag, which was created for this purpose: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

The template tag is even allowed to contain what would be invalid HTML elsewhere, e.g. a td tag outside a table.

rybo111
  • 12,240
  • 4
  • 61
  • 70
27

Remove the line breaks.

http://jsfiddle.net/DmERt/

var large = '<div class="accordian_container"><a href="#" class="accordian_trigger"><h4>Co-Borrower Information</h4></a><hr/><div class="accordian_item" id="accord_item_2"><label> First Name</label><br/><input type="text"/><br/><label>Middle Name</label><br/><input type="text"/><br/><label>Last Name</label><br/><input type="text" /><br/><label>Home Number</label><br/><input type="text"/><br><label>Work Number</label><br/><input type="text"/><br><label>Cell Number</label><br/><input type="text"/><br></div></div>';

$('#accordion_container').append(large);​
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • 1
    `$('#accordion_container').append(large);` as that is how he had it posted. ( Provided he has an element with ID `accordion_container`) – Selvakumar Arumugam May 25 '12 at 18:17
  • This would append it to all div elements. Not something you would usually want. – nunespascal May 25 '12 at 18:19
  • 1
    It was a sample pulled from my fiddle example. The question appends it to an ID, I assumed that the person asking would have enough common sense to append it where they want to append it. Updating. – Kevin B May 25 '12 at 18:21
  • I believe it will fail altogether if he has 2 identical id's – David May 25 '12 at 18:24
  • Sorry that was unintentional - I have fixed the double ID issue. The line breaks were the route of my problem with the script however. – Thomas May 25 '12 at 18:35
  • You should never have to look for multiple identical ID's since that is so far away from standard many browsers will not support it. – Filip Haglund Mar 18 '13 at 20:23
8

It's my understanding that if you want to put your long string on multiple lines that it's more efficient to use an array of strings and join them.

var bigString = [
    'some long text here',
    'more long text here',
    '...'
];
$('#accordion_container').append(bigString.join(''));
David
  • 1,887
  • 2
  • 13
  • 14
8

You can use a backslash at the end of each line.

http://davidwalsh.name/multiline-javascript-strings

var multiStr = "This is the first line \
This is the second line \
This is more...";
Oliver Konig
  • 1,035
  • 2
  • 14
  • 17
  • I use what Oliver said all the time in JS because it looks more human readable. And you don't have to keep defining Quotes every line and concatenating: Here is my http://jsfiddle.net/49gpqwua/ (JSFiddle) – Preactive Sep 05 '15 at 15:50
8

Another alternative is Template literals with back-ticks:

var large = `some long text here
some long text here
some long text here`;

It's a fairly new syntax and not supported in IE though.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

gustavwiz
  • 187
  • 2
  • 6
  • Note that the name has been changed to **template literals**, and that in that example the spaces for indenting the second two lines would be a part of the end string. Still a valid answer, just worth noting those two things. – Jimbo Jonny Mar 29 '16 at 15:01
  • This is solid...Thanks. – Francisco Apr 23 '18 at 16:54
6

Use Template literals Template literals are literals delimited with backticks (`), allowing embedded expressions called substitution

var test = `<div class="question-content"> <p>  ${mydata.commented.comment}</p></div> <div class="about-info">
                    <div class="count-section">
                    <button id="clike-button" value={{comment.id}}><i class="fas fa-arrow-up"></i></button>

                    <h3 id="clike_count">{{ question.clike_count }}</h3>
                    <button id="cdislike-button" value={{comment.id}}><i class="fas fa-arrow-down"></i></button>

                </div>
                            <div class="user-profile">
                                <img src="{% static 'img/profile-pic.png' %}" alt="">
                                <div class="user-info">
                                    <p> ${mydata.user}</p>
                                    <p class="user-badge">
                                    <p class="user-badge"> <span style="padding-left: 2px;">13.1k</span><i
                                            class="fas fa-circle gold"></i> <span> 2</span> <i class="fas fa-circle silver"></i>
                                        <span>
                                            7</span> <i class="fas fa-circle bronze"></i> <span>56</span>
                                    </p>
                                </div>
                            </div></div> `;
                $("#commentlist").append(test)

https://i.stack.imgur.com/5BZHB.png

hellbnsdfsadf
  • 61
  • 1
  • 1
  • Upvoted this answer for the Backticks trick. Other answers are about Template literals but I couldn't use them until I noticed the backticks after reading your answer. – gael Nov 24 '21 at 09:40
2

Javascript have the option to extend multiple lines/HTML section into a single line, for each line of HTML row add backslash() to identify that its continue line.

Note :-The only thing to consider while append lines are the single quote and double quote. If you start with the single quote, then use double quote in the internal string or vice-versa, otherwise, line is break and do not get the proper result.

$(element).append('<div class="content"><div class="left"></div><div class="right"></div></div>');

Javascript syntax

 var str = ' <div class="content"> \
<div class="left"> \
</div> \
<div class="right"> \
</div> \
</div> ';

 document.getElementsByName(str).html(str);
 //or
 document.getElementsById(str).html(str);

Jquery syntax

 $(element).append(' \
  <div class="content"> \
    <div class="left"> \
    </div> \
    <div class="right"> \
    </div> \
  </div> \
');

Or you can use a html template for this as mention in 3rd link via jquery

$("#div").load("/html_template.html");

http://www.no-margin-for-errors.com/blog/2010/06/17/javascript-tip-of-the-day-extending-a-string-across-multiple-lines/

Appending multiple html elements using Jquery

spread html in multiple lines javascript

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
2

By default, the HTML code containing wraps cannot be used with append/prependdirectly use 'or". However currently there are following methods to do that:

  1. Use "+" to join HTML code pieces.

  2. Use "\" to escape.

  3. Use "`" (back-tick, grave accent), do not need any extra operations. This method is supported from ES2015/ES6 (Template literals).

  4. Add a hidden tag containing the same HTML code you need, e.g. <p id="foo" style="display:none;">, then use.append($('#foo').html());.

    Now post some use scenarios to the first three methods metioned above (just run them in the console of Chrome browser.): enter image description here

We can see their differences clearly.

Bravo Yeung
  • 8,654
  • 5
  • 38
  • 45
1

You can also clone the div with jQuery and then append the clone--way less messy.

var accordionClone = $('.accordion_container').clone();
$('#accordion_container').append(accordionClone);
alexoviedo999
  • 6,761
  • 1
  • 26
  • 17
1

just add like this $(#element).append(large_html),large_html in special character(``) and thank me later.

Chidananda Nayak
  • 1,161
  • 1
  • 13
  • 45
0

If line-breaks are an issue just use innerHTML, works in every browser since IE5:

$('#accordion_container')[0].innerHTML += large;​

Or, for collections:

$('.accordion_container').forEach(function () {
    this.innerHTML += large;​
});
Pete B
  • 1,709
  • 18
  • 11