Search code examples
javascriptjqueryinsertafterjquery-after

$fn.insertAfter() and $fn.after() Jquery


I understand that $fn.insertAfter() is used to insert element after the element supplied as the argument. How's $fn.after() different from it?


Solution

  • $.fn.after()help inserts an element after the target element, on which you call it.

    $('div').after('<div>new div</div>');
    

    whereas, $.fn.insertAfter inserts the target element after the node you specify:

    $('<div>new div</div>').insertAfter($('#someid'));
    

    The latter is mostly prefered, because you keep a reference to the newly created element and can chain more methods on it. So for instance:

    $('<div>new div</div>')
       .insertAfter($('#someid'))
       .attr('foo', 'bar')
       .css({
          'background-color': 'red'
       });
    

    is possible. You cannot do that with .after()help. The same thing is for .append()help / .appendTo()help and .insertBefore()help / .before()help