Make sure that the previous element is removed from the page before the next is inser...
[jquery.git] / src / manipulation.js
index 105a0a9..7128d11 100644 (file)
@@ -168,21 +168,8 @@ jQuery.fn.extend({
 
                // Copy the events from the original to the clone
                if ( events === true ) {
-                       var orig = this.find("*").andSelf(), i = 0;
-
-                       ret.find("*").andSelf().each(function(){
-                               if ( this.nodeName !== orig[i].nodeName ) { return; }
-
-                               var events = jQuery.data( orig[i], "events" );
-
-                               for ( var type in events ) {
-                                       for ( var handler in events[ type ] ) {
-                                               jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
-                                       }
-                               }
-
-                               i++;
-                       });
+                       cloneCopyEvent( this, ret );
+                       cloneCopyEvent( this.find("*"), ret.find("*") );
                }
 
                // Return the cloned set
@@ -223,7 +210,17 @@ jQuery.fn.extend({
 
        replaceWith: function( value ) {
                if ( this[0] && this[0].parentNode ) {
-                       return this.after( value ).remove();
+                       return this.each(function(){
+                               var next = this.nextSibling, parent = this.parentNode;
+
+                               jQuery(this).remove();
+
+                               if ( next ) {
+                                       jQuery(next).before( value );
+                               } else {
+                                       jQuery(parent).append( value );
+                               }
+                       });
                } else {
                        return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
                }
@@ -284,6 +281,24 @@ jQuery.fn.extend({
        }
 });
 
+function cloneCopyEvent(orig, ret) {
+       var i = 0;
+
+       ret.each(function(){
+               if ( this.nodeName !== orig[i].nodeName ) {
+                       return;
+               }
+
+               var events = jQuery.data( orig[i], "events" );
+
+               for ( var type in events ) {
+                       for ( var handler in events[ type ] ) {
+                               jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
+                       }
+               }
+       });
+}
+
 function buildFragment(args, nodes, scripts){
        var fragment, cacheable, cached, cacheresults, doc;