jQuery Snippets: swap
Sunday, June 10, 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.
Posted in jQuery with 5 comments
You can also do this without cloning either element (probably a little faster):
By Steve Clay on Saturday, June 23, 2007 at 09:46 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.)
By Steve Clay on Saturday, June 23, 2007 at 09:52 AM
I tried to swap elements inside a select box, but they lose the “selected” attribute.
By Lorenzo on Wednesday, September 10, 2008 at 08:11 AM
@Lorenzo, Yeah browsers are very sporadic about how they handle form element attributes like selected when you start cloning and moving them around.
By Brandon Aaron on Wednesday, September 10, 2008 at 09:14 AM
In case anyone is interested, here is a working snippet of Steves version:
The original version that clones the elements messes with attached events..
By MelTraX on Wednesday, September 10, 2008 at 10:14 AM