Adding multiple html elements using jQuery

I am new to jQuery and wondering if anyone can advise me on best practice ...

I want to add a div element to a page containing a lot of html and am not sure if the best way to achieve this is ....... or if it is appropriate using jquery ...

For example, if I would like to add the following code to a page using jquery, then 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> 
+7
jquery
source share
3 answers

If you want to add HTML as is, 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 the body to another DOM element / selector according to your requirements.

Or, if you already have a div element with the identifier "test" in the document, you can set the content using the html () function, as shown 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>'); 
+17
source share
 $("#id_of_div").append($("#id_of_div_that_you_wanna_append").html()); 
+4
source share
 $("#test").append("YOUR CONTENT GOES HERE"); 
+3
source share

All Articles