Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending multiple html elements using Jquery

Tags:

jquery

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>
like image 263
namtax Avatar asked Dec 01 '09 10:12

namtax


People also ask

Can you append multiple items jQuery?

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.

What is append in jQuery?

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.


2 Answers

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>');
like image 98
Technowise Avatar answered Sep 22 '22 11:09

Technowise


$("#id_of_div").append($("#id_of_div_that_you_wanna_append").html());
like image 25
Tommaso Taruffi Avatar answered Sep 24 '22 11:09

Tommaso Taruffi