开发者

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

开发者 https://www.devze.com 2023-02-09 19:44 出处:网络
I understand that $fn.insertAfter() is used to insert element after the element supplied a开发者_运维技巧s the argument. How\'s $fn.after() different from it?$.fn.after()help inserts an element after

I understand that $fn.insertAfter() is used to insert element after the element supplied a开发者_运维技巧s the argument. How's $fn.after() different from it?


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


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>');


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消