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()

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

append()

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

$(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:

$(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:

$(function(){
    var list = $('ul.list li.foobar');
    $(list).after('Item After');
});
Share Comments
comments powered by Disqus