Codementor Events

jQuery Tutorial: Understanding .append(), prepend(), .after() and .before()

Published Jan 12, 2017Last updated Jan 18, 2017
jQuery Tutorial: Understanding .append(), prepend(), .after() and .before()

I have been a software developer for quite awhile now and every time I need to do something related to .append() and prepend(), I always find myself Googling about it. It's not that I don't know these things, but it's easy to get them mixed up. That is why I think I should share what I have learned over the years about .append() andprepend()`.

Let's getting started

.append() & .prepend()

  • .append() puts data inside an element at the last index; while
  • .prepend() puts the prepending element at the first index.
 <div class='a'> //<---you want div c to append in this
  <div class='b'>b</div>
</div>

Executing .append()

It will look like this:

 $('.a').append($('.c'));

And after execution...

<div class='a'> //<---you want div c to append in this
  <div class='b'>b</div>
  <div class='c'>c</div>
</div>

Executing .prepend()

It will look like this:

$('.a').prepend($('.c'));

And after execution...

<div class='a'> //<---you want div c to append in this
  <div class='c'>c</div>
  <div class='b'>b</div>
</div>

.after() & .before()

  • .after() puts the element after the element
  • .before() puts the element before the element

Using .after()

$('.a').after($('.c'));

After execution...

<div class='a'>
  <div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed here

Using .before()

$('.a').before($('.c'));

After execution...

<div class='c'>c</div> //<----this will be placed here
<div class='a'>
  <div class='b'>b</div>
</div>

Wrapping up

If you think about it, it's quite understandable and I think all web developer should just try and keep this at the back of their mind—but I wonder why I keep forgetting about it 😦

Discover and read more posts from Olatunde Owokoniran
get started
post comments2Replies
Sagar Behera
2 years ago

Helpful content it was.

Yogi S.
6 years ago

Hello Olatunde, Very nice tutorial on jQuery. I think jQuery Append and prepend methods are sufficient and there is no need to learn .after() and .before().