jQuery Snippets: swap
June 10th, 2007
Internet Explorer provides a handy little method called swapNode. This method allows you to swap one element with another. Now the functionality of swapNode is available in a jQuery method called swap. The swap method can take a selector, an element or a jQuery object. It will take the first matched elements and swap them. The usage is easy. For example if we wanted to swap the first paragraph with the last paragraph, it would look like this.
-
$('p:first').swap('p:last');
The swap method is pretty straight forward.
-
jQuery.fn.swap = function(b) {
-
b = jQuery(b)[0];
-
var a = this[0],
-
a2 = a.cloneNode(true),
-
b2 = b.cloneNode(true),
-
stack = this;
-
-
a.parentNode.replaceChild(b2, a);
-
b.parentNode.replaceChild(a2, b);
-
-
stack[0] = a2;
-
return this.pushStack( stack );
-
};
You can download the source code and see an example here.

June 23rd, 2007 at 9:46 am
You can also do this without cloning either element (probably a little faster):
// t will be a placeholder node
var t = a.parentNode.insertBefore(a, document.createTextNode(''));
b.parentNode.insertBefore(a, b);
a.parentNode.insertBefore(b, t);
a.parentNode.removeChild(t);
June 23rd, 2007 at 9:52 am
oops, I really messed that up but you get the idea. insertBefore removes the element from the old location for you when it inserts it (as does appendChild, etc.)