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');
Comments
Nico FLemming
-
Sep 29, 2010
@
2:51 AM
Permalink
Alexander Hjelmeseth
-
Feb 11, 2011
@
3:02 PM
Permalink
Axel
-
Feb 14, 2011
@
9:13 AM
Permalink
Ryan Charmley
-
Aug 24, 2011
@
3:42 PM
Permalink
element1 = $("#element1");
element2 = element1.next();
element2.insertBefore("#element1");
works everywhere, if u want to swap two elements.. no effects:)
dhanesh mane
-
Sep 23, 2011
@
12:49 PM
Permalink

http://www.vertstudios.com/blog/swap-jquery-plugin...