tags:

views:

189

answers:

3

Hi there...

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>
+1  A: 
$("#test").append("YOUR CONTENT GOES HERE");
MattC
+1  A: 
$("#id_of_div").append($("#id_of_div_that_you_wanna_append").html());
tommaso
is it best to use a div already in the html, or to use Jquery to create the html on the fly for you to use...eg $('<div id ="test><h1>This is the test</h1></div>).appendTo('body')Sorry, am trying to make this appear as a code block, but doesnt seem to be working
namtax
You don't need the .html() at the end.
antti_s
You need the .html() at the end if you're planning on multiple copies.
Magnar
+2  A: 

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>');
Technowise
is this a better method than putting the content into an joined array?
namtax
Not sure what you mean. Are you referring to slashes used for each line-breaks?
Technowise
i mean doing this as an alternative...var array1 = ['<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>']; $(array1.join('')) .appendTo('#test');
namtax
I don't know why you'd put them in an array. Anyway, its not any 'better' than your method.Its just a matter of preference, and I prefer the method I wrote above.
Technowise