A jQuery insert text example

jQuery insert text FAQ: How do I insert text into a section of my HTML page using jQuery?

I ran into a situation recently with my new website (see my new Alaska online store demo) where I couldn't figure out how to do something with a shopping cart tool named Ubercart, so rather than fight it any longer, I decided to just use jQuery to insert text into my HTML document right where I wanted it.

jQuery insert text - Use the prepend function

At first I thought I needed to use the jQuery text function, but I quickly remembered that function actually replaces text, and specifically does not perform an insert. To do a jQuery insert text action, what you really need to do is use the jQuery prepend function, like this:

jQuery('div.view-content').prepend('<p id="welcome">Welcome to our demo store.</p>');

In that jQuery insert text example, I'm saying:

  • Search the DOM for a <div> tag with the class named "view-content". (I knew I only had one match to worry about, so that's all the searching I needed to do.)
  • Insert the following <p> tag text into the beginning of that <div> section.

Again, you don't want to use the jQuery text function here, because that actually replaces all the content in your <div>.

My complete jQuery insert text example

If you've used jQuery before, all you probably needed to see was that one line of code, but if you're just getting started with jQuery, it may be helpful to see all the code I used, let's take a look at it.

First, Drupal 7 was kind enough to load jQuery for me, like this:

<script type="text/javascript" src="http://www.matsuvp.com/misc/jquery.js?v=1.4.4"></script> 

Then at the bottom of my HTML page, just before the closing <body> tag, I inserted this block of code:

<script type="text/JavaScript"> 
  jQuery(document).ready(function(){
    jQuery('h1#page-title').hide();
    jQuery('div.view-content').prepend('<p id="welcome">Welcome to our demo store. Click the About link above for more information.</p>');
  });
</script>

As you can see, the first thing I did was to hide the <h1> tag on that page, and then I did my jQuery insert text command on the following line of code with the jQuery prepend function.

jQuery insert text example - Summary

I hope this jQuery insert text example has been helpful. Just remember to use the jQuery prepend function instead of the jQuery text function, and your insert text code should work just fine.