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.
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:
Again, you don't want to use the jQuery text function here, because that actually replaces all the content in your <div>.
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:
Then at the bottom of my HTML page, just before the closing <body> tag, I inserted this block of code:
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.
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.