A quick and dirty swap() method for jQuery
Categories:
jQuery
A few weeks ago I needed a jQuery swap() function for some drag and drop code I was writing. While it would have been easy enough to whip up a quick little function, I found this little snippet courtesy of Brandon Aaron's blog:
jQuery.fn.swap = function(b){
b = jQuery(b)[0];
var a = this[0];
var t = a.parentNode.insertBefore(document.createTextNode(''), a);
b.parentNode.insertBefore(a, b);
t.parentNode.insertBefore(b, t);
t.parentNode.removeChild(t);
return this;
};
b = jQuery(b)[0];
var a = this[0];
var t = a.parentNode.insertBefore(document.createTextNode(''), a);
b.parentNode.insertBefore(a, b);
t.parentNode.insertBefore(b, t);
t.parentNode.removeChild(t);
return this;
};
This particular method only works with the first DOM element in each of the jQuery objects. Using the code is easy enough, the following example would swap the first and last nodes in an unordered list who's id is "list".
$('ul#list > li:first').swap('ul#list > li:last');
