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');
});
Pedro Luz
A personal blog by Pedro Luz about coding, coding, habit building, and a few things more.(Psst... I am open to opportunities.)
Reach out to me on your favorite social :)© 2020 Pedro Luz