jQuery: What's the difference between after() and insertAfter()

后端 未结 11 667
孤街浪徒
孤街浪徒 2021-01-31 07:42

jQuery has an .after() method, and also an .insertAfter() method.

What\'s the difference between them? I think I can use .after()

11条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 08:04

    After() and Insertafter() both appends an element, the major change will come for chaining

    In after() you are appending the new element after your selector and then if you are using chain for the element then any function you used will fire on the selector not on the newly added element, and the opposite will performed in insertAfter() in which the chaining will performed on the newly added element for example,

    After() and InsertAfter()

    HTML

    After Div
    ------------------------------------------------------
    Insert after div

    SCRIPT

    var p='

    Lorem ipsum doner inut..

    '; $('.after').after(p)//chaining, performed on .after div not on p .css('backgroundColor','pink'); //you can chain more functions for .after here $(p).insertAfter('.insertafter')//chaining, performed on p not on .insertafter div .css('backgroundColor','yellow'); // here you can chain more functions for newly added element(p)

    See above the selector and contents are changing in both functions. The same will apply on the list of following:

    1. before() vs insertBefore()
    2. append() vs appendTo()
    3. prepend() vs prependTo()
    4. and after() vs insertAfter(), obviously.

    Live Demo

    If you want to see both, performance wise then after() is faster than insertAfter() See after-vs-insertafter-performance.

提交回复
热议问题