Im trying to append a large block of text using jquery\'s append().
$(\'#add_contact_btn\').click(function(event) {
event.preventDefault();
var large =
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...";
By default, the HTML code containing wraps cannot be used with append/prepend
directly use 'or"
. However currently there are following methods to do that:
Use "+" to join HTML code pieces.
Use "\" to escape.
Use "`" (back-tick, grave accent), do not need any extra operations. This method is supported from ES2015/ES6 (Template literals).
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.):
We can see their differences clearly.
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;
});
You should 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.
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
.
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(''));
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