0

If there is something like this:

<div id="one">
  ...other elements inside...
</div>

<div id="two">
  ...other elements inside...
</div>

I know you can do:

$("#two").before($("#one"));

But what about this situation when you have something like this:

<div id="one">
  ...other elements inside...
</div>

<div id="two">
  ...other elements inside...
</div>

<div id="three">
  ...other elements inside...
</div>

<div id="four">
  ...other elements inside...
</div>

<div id="five">
  ...other elements inside...
</div>

<div id="six">
  ...other elements inside...
</div>

<div id="seven">
  ...other elements inside...
</div>

<div id="eight">
  ...other elements inside...
</div>

and you want to swap #eight and #four how would you do that in Jquery? Each div contains a lot of code and this code is dynamically changed so only the #one, #two, etc. of the main divs are stable and callable.

John Doerthy
  • 445
  • 5
  • 14

1 Answers1

0

Thanks to bwegs for the find. Adding for completeness.

function swapElements(elm1, elm2) {
    var parent1, next1,
    parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}

Note that it's fine if the reference element (next1 or next2 above) is null; insertBefore handles that correctly (by adding at the end of the parent, like appendChild would).

noctrnal
  • 191
  • 4