Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery move DOM element inside parent

Tags:

jquery

element

Is there a simple way to move an element inside its own parent?

Like this...

from:

<div class="test">hello 1</div>
<div class="test">hello 2</div>
<div class="test">hello 3</div>

to:

<div class="test">hello 1</div>
<div class="test">hello 3</div>
<div class="test">hello 2</div>

Either move a div UP or DOWN one step, or using the index to appendTo in a specific position.

like image 387
user1121487 Avatar asked Jun 19 '12 09:06

user1121487


2 Answers

You should be able to use .prev() and .next() like this (here as a jQuery function):

$.fn.moveUp = function() {
    $.each(this, function() {
         $(this).after($(this).prev());   
    });
};
$.fn.moveDown = function() {
    $.each(this, function() {
         $(this).before($(this).next());   
    });
};
$("div:eq(2)").moveUp(); //Would move hello 3 up
$("div:eq(0)").moveDown(); //Would move hello 1 down

JSFiddle Demo

like image 98
h2ooooooo Avatar answered Nov 16 '22 03:11

h2ooooooo


Try

$("div:eq(2)").after($("div:eq(0)"));

or

$("div:eq(2)").before($("div:eq(1)"))

Remembering that :eq() is zero based.

like image 3
472084 Avatar answered Nov 16 '22 04:11

472084