Adding HTML content dynamically using jQuery append() method

By Faruque Ahamed Mollick

Here in this tutorial, I am going to show you how to add HTML content dynamically using jQuery append method. The append method of jQuery actually adds specified content at the end of an element that is selected with jQuery selector.

Here I am going to show you some example code so that you will understand the usage of the jQuery append() method.



Send AJAX request every n seconds using jQuery

Simple Animation Example Using jQuery

Suppose we have an HTML paragraph just like below:

<p>Below is the HTML content using jQuery append<br/></p>

Now we are going to use the jQuery append method to add content after the above paragraph. Below is the given JavaScript code for jQuery:

<script type="text/javascript">
  $(document).ready(function(){
      $("p").append(" <b>This text come from jQuery append method.</b>");
    });
</script>

Now you will see that the content added by the jQuery append method and the output now is:

Below is the HTML content using jQuery append
This text come from jQuery append method.


So you have seen how jQuery append method work from the simple above example.

Adding content on clicking an element

Now we are going to see the append working on click method. That means, when someone clicks an HTML element, the append method will add HTML content dynamically after a specified HTML tag.

AJAX search from MySQL database in PHP example

Retrieve the width of div element in JavaScript

We have the HTML that is given below:

<ul>
    <li>This is an item</li>
</ul>
<button id="button">Add item</button>

Now we are going to use jQuery append method to add item after the <ul> tag on clicking the button with id “button”. Whenever the button will be clicked, the append method will add HTML item automatically. To do it, we are going to use the jQuery code that is given below:

<script type="text/javascript">
$(document).ready(function(){
    $("#button").click(function(){
        $("ul").append("<li>this item added with append</li>");
    });
});
</script>

Now if you test it, you will see that the <li> item added every time you click the button. It will not remove the previously added item. It will keep all the previous items and add the new one whenever you click the button.

The jQuery append has lots of real-life use. For example, using append method multiple fileĀ uploading fields can be generated, multiple form input fields can be generated and so on which you may see on many websites.

Leave a Reply

Your email address will not be published. Required fields are marked *