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;
};

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

Comments

Joseph McCullough's Gravatar Cool function. If you're wanting to swap two elements selected within a jQuery object, you can use this method

http://www.vertstudios.com/blog/swap-jquery-plugin...
Nico FLemming's Gravatar Events and a possible focus (if swapepd object ist an input field) will be lost during swapping!
Alexander Hjelmeseth's Gravatar Thanks. A neat function. Tried to do this in php when i figured it might be someone who'd made a solution with jquery. If you want to swap specific items, you have to add classes or id's to these. It's also possible to swap between different ul's as long as they share the same class-name.
Axel's Gravatar Events won't be lost if you use live()
Ryan Charmley's Gravatar Worked like a dream! Thank you!!!
dhanesh mane's Gravatar I did it simply using following code..


element1 = $("#element1");
element2 = element1.next();
element2.insertBefore("#element1");

works everywhere, if u want to swap two elements.. no effects:)

Add Comment

Leave this field empty


If you subscribe, any new posts to this thread will be sent to your email address.