From 8660ea1ab61dd16aec1ed24ec549c6258292b96a Mon Sep 17 00:00:00 2001
From: Noah Sloan <noah.sloan@gmail.com>
Date: Mon, 1 Feb 2010 21:48:05 -0500
Subject: [PATCH] Only detach the incoming elements to replaceWith if they're
 DOM nodes. Fixes #5986.

---
 src/manipulation.js       |    9 +++++----
 test/unit/manipulation.js |   10 ++++++++--
 2 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/src/manipulation.js b/src/manipulation.js
index 2dccc75..6f0373d 100644
--- a/src/manipulation.js
+++ b/src/manipulation.js
@@ -268,16 +268,17 @@ jQuery.fn.extend({
 		if ( this[0] && this[0].parentNode ) {
 			// Make sure that the elements are removed from the DOM before they are inserted
 			// this can help fix replacing a parent with child elements
-			if ( !jQuery.isFunction( value ) ) {
-				value = jQuery( value ).detach();
-
-			} else {
+			if ( jQuery.isFunction( value ) ) {
 				return this.each(function(i) {
 					var self = jQuery(this), old = self.html();
 					self.replaceWith( value.call( this, i, old ) );
 				});
 			}
 
+			if ( typeof value !== "string" ) {
+				value = jQuery(value).detach();
+			}
+
 			return this.each(function() {
 				var next = this.nextSibling, parent = this.parentNode;
 
diff --git a/test/unit/manipulation.js b/test/unit/manipulation.js
index f921ea1..41ce8bb 100644
--- a/test/unit/manipulation.js
+++ b/test/unit/manipulation.js
@@ -650,7 +650,7 @@ test("insertAfter(String|Element|Array&lt;Element&gt;|jQuery)", function() {
 });
 
 var testReplaceWith = function(val) {
-	expect(15);
+	expect(17);
 	jQuery('#yahoo').replaceWith(val( '<b id="replace">buga</b>' ));
 	ok( jQuery("#replace")[0], 'Replace element with string' );
 	ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after string' );
@@ -661,6 +661,12 @@ var testReplaceWith = function(val) {
 	ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after element' );
 
 	reset();
+	jQuery("#main").append('<div id="bar"><div id="baz">Foo</div></div>');
+	jQuery('#baz').replaceWith("Baz");
+	equals( jQuery("#bar").text(),"Baz", 'Replace element with text' );
+	ok( !jQuery("#baz")[0], 'Verify that original element is gone, after element' );
+
+	reset();
 	jQuery('#yahoo').replaceWith(val( [document.getElementById('first'), document.getElementById('mark')] ));
 	ok( jQuery("#first")[0], 'Replace element with array of elements' );
 	ok( jQuery("#mark")[0], 'Replace element with array of elements' );
@@ -721,7 +727,7 @@ test("replaceWith(String|Element|Array&lt;Element&gt;|jQuery)", function() {
 test("replaceWith(Function)", function() {
 	testReplaceWith(functionReturningObj);
 
-	expect(16);
+	expect(18);
 
 	var y = jQuery("#yahoo")[0];
 
-- 
1.7.10.4