jQuery: swapping elements

Swapping elements with jQuery simply means replacing one element with another. This can be actually done with the replaceWith() method combined with the clone() method. In fact, we need to have a copy of the replaced element and a copy of its replacement. We can write the following mini-plugin to accomplish this task:

(function($) {


$.fn.swapElements = function(to) {

    return this.each(function() {
    
        var copyTo = $(to).clone(true);
        var copyFrom = $(this).clone(true);
        $(to).replaceWith(copyFrom);
        $(this).replaceWith(copyTo);
    });
};

})(jQuery);

A simple demo:

<div id="gallery">
 <img src="pics/1.jpg" alt="" />
 <img src="pics/2.jpg" alt="" />
</div>
$(function() {

  $('img:first', '#gallery').one('click', function() {
  
    var $img = $(this);
    var next = $img.next();
  
    if(next !== null) {
    
      $img.swapElements(next);
    
    
    }  
  
  });
  
});

You can see this demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.