Am new to jQuery and wondering if any could advise me on best practise...
I am looking to append a div element to the page, which contains a lot of html and not sure wha
With ES6 (ECMAScript 2015) you can now use the backticks to surround all the HTML even with single or double quotes (useful also to add variables inbetween).
However, since the question seemed to focus on adding the entire block after some existing element, perhaps the after method would be more suitable than the append one in this case. This is the difference between them (run the snippet):
let $num = 0;
$('main').append(`
<article>
<h2>Appended ${++$num}</h2>
<p>Using 'single' and "double-quotes" without escaping!</p>
</article>
<article>
<h2>Appended ${++$num}</h2>
<p>Using 'single' and "double-quotes" without escaping!</p>
</article>
`).after(`
<footer>
<h2>Added after main</h2>
<p><b>${++$num} blocks</b> of multiple elements were added through jQuery</p>
</footer>
`);
article {background: #eee;border:1px solid #000;padding:1rem}
main {background: #ccc;padding:1rem}
body {background: #aaa;padding:1rem}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<h1>Main section</h1>
<article>
<h2>jQuery</h2>
<p>Adding multiple elements...</p>
</article>
</main>
You can also use the equivalent insertAfter and appendTo if you prefer this alternative syntax: $('<p>my html</p>').insertAfter('main')
The jQuery object containing the HTML blocks to add goes first and you only need to reference the string in the method's parameter.
$("#test").append("YOUR CONTENT GOES HERE");
$("#id_of_div").append($("#id_of_div_that_you_wanna_append").html());
Currently there are following methods:
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 you want to add the HTML as it is, then just use the jQuery append function. For example:
$('body').append('
<div id="test">\
<h1>This is the test</h1>\
<p>Hello, just a test</p>\
<a href="www.test.com">Click me</a>\
<a href="www.test.com">Click me again</a>\
</div>');
Change the selector from body to other DOM element/selector according to your requirement.
Or if you already have the div element with ID "test" in the document, then you can set the content using the html() function like below:
$("#test").html('<h1>This is the test</h1>\
<p>Hello, just a test</p>\
<a href="www.test.com">Click me</a>\
<a href="www.test.com">Click me again</a>');