jQuery Add To Div Examples

In jQuery, Tips and Tricks by March 2nd, 2013

371 Views

While working with jQuery, it may be desirable at times to add new data or info to a div. This is true especially when working with databases or with dynamic data. So in this article, I am going to share with you how to use jQuery to add to div. You can add another element or html or text. Read on to find out more.

How to use jQuery to add to div

So let’s see how we can do that by means of examples. Consider that we have a div with the ID “my_div”. I would now like to add a different element to this div. I would like to add a paragraph to div when a button is clicked. Also to illustrate that the paragraph is being added, I am adding red background color to the paragraph.

When the button is clicked, note that the background color of the div. What internally happens is that instead of just directly adding the paragraph to the div (as you would normally expect), jQuery merely adds the styling associated with it and not the “p” tag itself.

Example: Add content, HTML tags, etc. to div using jQuery

Conclusion:

Using .add() method to an element simply adds the properties of the new element to the existing element without adding the new element itself.

Your Turn!

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