skip to content

jQuery Snippets: swap

1 min read

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.

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

The swap method is pretty straight forward.

jQuery.fn.swap = function(b) {
    b = jQuery(b)[0];
    var a = this[0],
        a2 = a.cloneNode(true),
        b2 = b.cloneNode(true),
        stack = this;

    a.parentNode.replaceChild(b2, a);
    b.parentNode.replaceChild(a2, b);

    stack[0] = a2;
    return this.pushStack( stack );
};

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