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 what the best way to achieve this is....or if it is advisable using jquery...
For example, if I wanted to append the following code to the page using jquery, what is the best way.
<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>
The append method allows you to append multiple elements or text nodes to a parent node. As you can see, you can supply an unlimited amount of arguments to the append() method and it will append everything to the parent.
jQuery append() Method The append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
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>');
$("#id_of_div").append($("#id_of_div_that_you_wanna_append").html());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With