jQuery Snippets: swap

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.

  1. $('p:first').swap('p:last');

The swap method is pretty straight forward.

  1. jQuery.fn.swap = function(b) {
  2.     b = jQuery(b)[0];
  3.     var a = this[0],
  4.         a2 = a.cloneNode(true),
  5.         b2 = b.cloneNode(true),
  6.         stack = this;
  7.    
  8.     a.parentNode.replaceChild(b2, a);
  9.     b.parentNode.replaceChild(a2, b);
  10.    
  11.     stack[0] = a2;
  12.     return this.pushStack( stack );
  13. };

You can download the source code and see an example here.

2 Responses to “jQuery Snippets: swap”

  1. Steve Clay Says:

    You can also do this without cloning either element (probably a little faster):

    // t will be a placeholder node
    var t = a.parentNode.insertBefore(a, document.createTextNode(''));
    b.parentNode.insertBefore(a, b);
    a.parentNode.insertBefore(b, t);
    a.parentNode.removeChild(t);

  2. Steve Clay Says:

    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.)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>