Published Jan 12, 2017Last updated Jan 18, 2017

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

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 😦

What to Do When Your Website is Broken
RESTful CRUD Operations in Meteor.js
Create an Alexa Skill Part 3: Writing a Lambda Function