Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery move element to last child position

Tags:

html

jquery

dom

Let's say I have a <div> that contains some random elements, but there is one element I've created with this unique selector : $('.myUniqueElement'). I want to use .insertAfter() to move this element at last child position in my <div> is that possible ? what is the solution ?

This is my solution: http://jsfiddle.net/silverlight/RmB5K/3/ is this OK ??

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'/>

Javascript:

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

CSS:

.myUniqueElement{color:red;}
like image 541
Omid Avatar asked Aug 25 '13 08:08

Omid


3 Answers

Try

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

or simple

$('my-div').append($('.myUniqueElement'))
like image 176
Arun P Johny Avatar answered Nov 15 '22 15:11

Arun P Johny


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');
like image 42
Alnitak Avatar answered Nov 15 '22 15:11

Alnitak


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/

like image 2
Omid Avatar answered Nov 15 '22 15:11

Omid