818Swapping div elements with jQuery

I found myself in need for swapping div elements. On the one hand, elements, which are situated next to each other (in the code), on the other hand I also wanted to swap only sub-elements of these divs.

How can this be done with jQuery?

Let's start with the first case, swapping adjunct divs.

...
...
...
...
...
// get a handle on the elements
var elements = $(".elements");

// let's assume, we want to swap #e2 and #e3
var leftElement = $(elements[2]);
var rightElement = $(elements[3]);

leftElement.insertAfter(rightElement); // inserts leftElement after rightElement

insertAfter takes the object, with with the method is associated (leftElement) and inserts the object's div after the div specified as a method argument. Here's more on SO about it.

In a previous version of the code, i mistakenly though, that it's necessary to replace the leftElement with the right one prior to inserting...

// NG
leftElement.replaceWith(rightElement);
leftElement.insertAfter(rightElement);

This also seemed to work ok. Only later I found out, that any jQuery data() objects connected to the rightElement will get wiped when replaceWith is being called.

Finally you'll also want to do an update to the elements array, to get them in their new order:

var elements = $(".elements");