How do I move div after its next div

Go To


How do I move a div after its next div. For instance I have 3 different div sitting here.

<div class="div1">Div1</div>
<div class="div2">Div2</div>
<div class="div3">Div3</div>

I wan to move first div after the second div. It means div2 will be first and div1 will be second. I have bunch of same html format.

I want to execute jquery something like

$(".div1").each(function() {

Let me know if this doesn't make sense.

2012-04-04 04:09
by Dips


you can get the .next() element, and place it .after()


you can .insertAfter() the .next() element

$(".div1").each(function() {
    var item = $(this);

    //either this:;

    //or this:

2012-04-04 04:19
by Joseph
I think you have that a bit backwards: - mu is too short 2012-04-04 04:21
i guess i did have it backwards. i was thinking if insertAfter(). thanks - Joseph 2012-04-04 04:23
I have to check them to make sure I get them right too : - mu is too short 2012-04-04 04:27
Good work mate - Dips 2012-04-04 04:36
Why not simplify it to this?

No need for the "each" right - Jargs 2015-04-17 22:35


Here is how you do cut paste operations with DOM in jQuery way.

Var temp=  $(“div1”).detach(); //Performs the cut operation
temp.insertAfter(“div2”);  //Does the paste
2012-04-04 04:21
by anuj_io
You don't need to detach, just $('.div1').insertAfter('.div2');​ is sufficient: - mu is too short 2012-04-04 04:23
I think your answer is the best M - Dips 2012-04-04 04:27
Detach will also copy along all the event handlers attached to that DOM element, not sure if just insertAfter would do, correct me if I am wrong - anuj_io 2012-04-04 04:27
no need to detach. if you check, they just move the elements - Joseph 2012-04-04 04:34
From jQuery official documentation: "The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time."

So lets say you have written a code for mousein and mouseout events using jQuery (can be counted as all jQuery data associated) , that handler would behave erratically if you don't use detach. Why do you think that jQuery folks would include a useless method and that too when you have remove() to perform the cut operation alone - anuj_io 2012-04-04 04:42

I'm not criticizing but $('.div1').insertAfter('.div2'); preserves the bindings unless I'm missing something: - mu is too short 2012-04-04 04:57
In this case OP doesn't want to insert the removed (or detached) element "at a later time" - the requirement is to move it immediately, and .insertAfter() (and several other methods) will do that - no need for .detach() for this purpose - nnnnnn 2012-04-04 04:59