Skip to content

Commit 2a6de9a

Browse files
committed
Make sure that the previous element is removed from the page before the next is inserted, in replaceWith. Using a variation of the patch by snaury. Fixes #2697.
1 parent aae0617 commit 2a6de9a

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/manipulation.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,17 @@ jQuery.fn.extend({
210210

211211
replaceWith: function( value ) {
212212
if ( this[0] && this[0].parentNode ) {
213-
return this.after( value ).remove();
213+
return this.each(function(){
214+
var next = this.nextSibling, parent = this.parentNode;
215+
216+
jQuery(this).remove();
217+
218+
if ( next ) {
219+
jQuery(next).before( value );
220+
} else {
221+
jQuery(parent).append( value );
222+
}
223+
});
214224
} else {
215225
return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
216226
}

test/unit/manipulation.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ test("insertAfter(String|Element|Array<Element>|jQuery)", function() {
466466
});
467467

468468
var testReplaceWith = function(val) {
469-
expect(12);
469+
expect(14);
470470
jQuery('#yahoo').replaceWith(val( '<b id="replace">buga</b>' ));
471471
ok( jQuery("#replace")[0], 'Replace element with string' );
472472
ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after string' );
@@ -491,6 +491,13 @@ var testReplaceWith = function(val) {
491491
var set = jQuery("<div/>").replaceWith(val("<span>test</span>"));
492492
equals( set[0].nodeName.toLowerCase(), "span", "Replace the disconnected node." );
493493
equals( set.length, 1, "Replace the disconnected node." );
494+
495+
var $div = jQuery("<div class='replacewith'></div>").appendTo("body");
496+
$div.replaceWith("<div class='replacewith'></div><script>" +
497+
"equals(jQuery('.replacewith').length, 1, 'Check number of elements in page.');" +
498+
"</script>");
499+
equals(jQuery('.replacewith').length, 1, 'Check number of elements in page.');
500+
jQuery('.replacewith').remove();
494501
}
495502

496503
test("replaceWith(String|Element|Array&lt;Element&gt;|jQuery)", function() {

0 commit comments

Comments
 (0)