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");

721jQuery’s Live Clicks

Update Since jQuery 1.7 live() is marked for deprecation and should not be used any more. Use on() instead. When content is dynamically created by jQuery it is not automatically inserted into the DOM. Therefore, if you dynamically add – for example – a link, and you want to capture a click on this link, it is necessary to use the live() function.it is necessary to use the on() function.


NG. The link is added to the container, but the click function is not called.
// $('.container > a').live('click', function(e) {	// pre jQuery 1.7
$(document).on('click', '.container > a', function(e){
	// do things
	e.preventDefault();
});
OK. The link is added to the DOM, and the click function is called. Yeah. Of course the same also goes for appended elements:
$("#container").append('');

// ...

// $('#container canvas').live('mousedown', function (e) {
$(document).on('click', '#container canvas', function(e){	// pre jQuery 1.7
	console.log(this.id);
});