Using jQuery Add HTML To Div

So far, we have seen lot of div manipulation stuff. We have added divs, added div to div, added text to div. etc. One of the key things would be to adding html to div. This may be immensely used when you try to create a specific feature where you would like to show the html source for display purposes.  This could also be used in applications like next-generation web editors or online HTML editors, etc. In this article, I am going to share with you very simple ways to use jQuery to add html to div. Examples follow.

How to use jQuery to add html to div

Let’s see how to do this by means of an example. Assume that we have a div with ID “my_div”. Let’s assume that you have some random HTML that you would like to add to this div.  Well so far, no confusion. But before we actually look at how we can add the html content to our target div, we need to consider some possibilities. They are:

  1. If the existing div does not contain any existing html, then we would expect our new html to show up in this div. Correct? Yes, it is.
  2. What happens if this div contains existing html/data already? What will happen to such html? What will happen to the new html that we are trying to add?

So because it could be any of the 2 possibilities, you need to determine what’s right for you. And only you can do that based upon the needs of your application. In order to cover all possibilities, I am going to share all possibilities with an example for each of them so that you can use whatever your application needs.

Example 1 – Add html to an empty div

Example 2 – Add html to a div containing existing html and append the new html to the existing html

Example 3 – Add html to a div containing existing html and overwrite the existing html with new html


1. If you are absolutely sure that there is no existing html in the div, use the code shown in the 1st example.

2. If you really want to overwrite the existing data with the new html, use the code shown in the 2nd example.

3. If you want to retain the existing data & simply append/add the new data to it, then use the code shown in the 3rd example.


There is no difference in the syntax used or in the procedure if you want to simply add html to an empty div or overwrite the existing html of a div. It is different only if you want to retain existing content & simply want to add new content on top of it.

Full source code to use jQuery to append html to div:

Your Turn!

Do you know of any other ways to use jQuery to add html to div? Feel free to share by commenting below.

Share your thoughts, comment below now!



CommentLuv badge