jQuery Add Text To Div Examples

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

519 Views

When working with divs in a webpage, divs with static data are ok. But what if you want to add new text to div? In this article, I am going to share very easy way to use jQuery to add text to div. Simple examples follow. So read on to find out more.

How to use jQuery to add text to div

Before we go ahead and start discussing the examples, let’s hold on for a moment and think about what we are trying to achieve. We want to add some custom text to a div. Pretty good, so far. Consider the 2 possibilities below:

  1. If the existing div does not contain any existing text, then we would expect our new text to show up in this div. Correct? Yes, it is.
  2. What happens if this div contains existing text/data already? What will happen to such text? What will happen to the new text 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. Hence, I am going to discuss both the possibilities. In fact, 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 text to an empty div

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

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

Complete source code to add custom text to div using jQuery:

Conclusion:

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

2. If you really want to overwrite the existing data with the new data, 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.

Note:

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

That’s it!

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