A quick and dirty swap() method for jQuery

Posted by Dan on Sep 24, 2008 @ 9:37 AM

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

Categories: jQuery


Comments for this entry have been disabled.