jquery move element to last child position

前端 未结 6 438
迷失自我
迷失自我 2021-01-01 10:40

Let\'s say I have a

that contains some random elements, but there is one element I\'ve created with this unique selector : $(\'.myUniqueElemen
相关标签:
6条回答
  • 2021-01-01 11:13

    In order to use insertAfter(), you must know the element after which you want to move your element to. And as you said you have random elements, and of course you don't know the current last element, so here what you can do.

    Clone your element that you want to move and append it to parent element.

    The jQuery code looks like this:

    $clone_elem = $('.myUniqueElement').clone();
    $('.myUniqueElement').remove();
    $('div').append($clone_elem);
    

    Checkout this fiddle

    0 讨论(0)
  • 2021-01-01 11:17

    Try

    var mydiv = $('my-div-selector');
    mydiv.find('.myUniqueElement').appendTo(mydiv)
    

    or simple

    $('my-div').append($('.myUniqueElement'))
    
    0 讨论(0)
  • 2021-01-01 11:20

    Vikas is right. However, probably this one is an improved version of it since the original element is removed, not its clone....

        $elem = $('.myUniqueElement')
        $('div').append($elem.clone());
        $elem.remove();
    
    0 讨论(0)
  • 2021-01-01 11:24

    This is my solution and I think this is the best way I can use .insertAfter():

    HTML:

    <div class='p'>
        <div class='myUniqueElement'>unique</div>
        <div>item</div>
        <div>item</div>
        <div>item</div>
    </div>
    <input type='button' id='b' value='Do'/>
    

    jquery:

    $('#b').on('click',function(){
        $('.myUniqueElement').insertAfter($('.p :last-child'))
    });
    

    The point is :last-child and this is the fiddle: http://jsfiddle.net/silverlight/RmB5K/3/

    0 讨论(0)
  • 2021-01-01 11:25

    There is no need to use .insertAfter. You should also not use .clone as it'll remove any attached data or events, unless you use .clone(true).

    Simply use .appendTo to add the target element to the div and it'll get detached from its original position and added as the last child of the div:

    $('.myUniqueElement').appendTo('#my-div');
    
    0 讨论(0)
  • 2021-01-01 11:37

    There is no need to call $ more than once, just move the element to the end of its parent:

    var myEl = $('.my-el-selector');
    myEl.appendTo(myEl.parent());
    
    0 讨论(0)
提交回复
热议问题