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

257 views Asked by At

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

4

There are 4 answers

1
jAndy On BEST ANSWER

$.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

0
Alan Haggai Alavi On

Quoting straight from the documentation:

The .after() and .insertAfter() methods perform the same task. The major difference is in the syntax—specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

0
Sem Vanmeenen On

This mentions that they perform the same task but have different syntax.

0
zzzzBov On

This is an example of the same thing, the difference is the context of the selector. insertAfter inserts the selected element after the parameter after inserts the parameter after the selected element.

$('<div id="foo"></div>').insertAfter('#bar');
$('#bar').after('<div id="foo"></div>');