jQuery prepend, append, before, after

jQuery prepend, append, before, after

They allow to add html to specific areas.

prepend()

Imagine that we have something like this list:

Item 1
Item 2
Item 3
Item 4

If we need to add a new list item ‘Item 0′ at the beginning, we can do it by using prepend()

10
11
12
13
$(function(){
  var list = $('ul.list');
  $(list).prepend('Item 0');
});

append()

Append works the same way, but adds to the end of the list

20
21
22
23
$(function(){
  var list = $('ul.list');
  $(list).append('Item 5');
});

before()

Image that you want to add a item to the list, before the the last item:

30
31
32
33
$(function(){
  var list = $('ul.list li:last');
  $(list).before('Item Before');
});

after()

Image that you want to add a item to the list, before the the last item:

40
41
42
43
$(function(){
    var list = $('ul.list li.foobar');
    $(list).after('Item After');
});