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() and
prepend()`.
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>
.append()
Executing 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>
.prepend()
Executing 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
.after()
Using $('.a').after($('.c'));
After execution...
<div class='a'>
<div class='b'>b</div>
</div>
<div class='c'>c</div> //<----this will be placed here
.before()
Using $('.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
Helpful content it was.
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().