he...">

JQuery move DOM element inside parent

Is there an easy 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> 

in

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

Either move the UP or DOWN div one step, or use the index for appendTo at a specific position.

+6
source share
3 answers

You can use .prev() and .next() like this (here as jQuery):

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

+12
source

Try

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

or

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

Recalling that: eq () is based on a zero value.

+3
source
 var child = $('#parent div'); // keep reference for further use child.eq(2).insertBefore(child.eq(1)); 

Demo

+2
source

Source: https://habr.com/ru/post/918455/


All Articles