Using jQuery’s append, prepend, html, and text

Programmers

jQuery Prepend append html text functionsjQuery is all about manipulating the page after it’s been downloaded: client-side changes to the coding. At some point in your work, you’ll probably need to add something to the page – and jQuery’s got you covered.

Whether you’re looking to add a Div based on a user’s interaction or modify the code without touching the original, there are three options in jQuery:

  1. Adding something inside
  2. Adding something outside
  3. Wrapping something

Each way has quite a few options, but in this post, we’re going to cover the most popular ways of adding jQuery inside of a Div (Option 1 above).

Append(“stuff to add here”)

Append will add whatever is in the quotes (single or double) at the very end of the Div, but still inside that Div.

Example Use:

$('#CoolWebsites').append('KimJoyFox.com');

Result:

<div id="CoolWebsites">
Cool.com
AnotherWebsite.com
KimJoyFox.com
</div>

Prepend(‘stuff to add here’)

Prepend does something of the opposite of append. It adds the information to the beginning of the Div, right after it opens.

Example Use:

$('#CoolWebsites').append('KimJoyFox.com');

Result:

<div id="CoolWebsites">
KimJoyFox.com
Cool.com
AnotherWebsite.com
</div>

HTML(‘stuff to add here’)

HTML is about replacing the information inside of a Div. For example, replacing a form that the user submitted with a “Thank You”.

Example Use:

$('#CoolWebsites').html('Thank You');

Result:

before

<div id="CoolWebsites">
Here's the information in this Div...
</div>

after

<div id="CoolWebsites">
Thank You
</div>

Text()

Text isn’t quite the same as the others. All the others deal with putting the information in somehow. Text deals with getting the information that’s already in the Div. Also, it takes no arguments – so don’t put anything between the parenthesis.

Example Use:

 var content = $('#CoolWebsites').text();
<div id="CoolWebsites">
Cool.com
</div>

Text didn’t change anything in the Div, but now you’ve got a variable “content” with the value of “Cool.com”.

Summary

Between append(), prepend(), html(), and text() you can manipulate to your heart’s content!

Comments
  • Paris says:

    I’m using prepend to insert text in a tab, but what’s inside the quotes gets automatically doubled. Do you know what may be going wrong?

    For example:

    $(‘#CoolWebsites’).prepend(‘KimJoyFox.com’);

    Result:

    KimJoyFox.comKimJoyFox.com
    Cool.com
    AnotherWebsite.com