Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

[1.9] make replaceWith() clone elements where required #920

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+27 −19
Split
View
@@ -276,32 +276,29 @@ jQuery.fn.extend({
value = jQuery( value ).detach();
}
- this.each( function( i ) {
- var next = this.nextSibling,
- parent = this.parentNode,
- // HTML argument replaced by "this" element
- // 1. There were no supporting tests
- // 2. There was no internal code relying on this
- // 3. There was no documentation of an html argument
- val = !isFunc ? value : value.call( this, i, this );
+ return this.domManip( [ value ], true, function( elem, i ) {
+ var next, parent;
if ( isDisconnected( this ) ) {
- // for disconnected elements, we replace with the new content in the set. We use
- // clone here to ensure that each replaced instance is unique
- self[ i ] = jQuery( val ).clone()[ 0 ];
+ // for disconnected elements, we simply replace with the new content in the set
+ self[ i ] = elem;
return;
}
- jQuery( this ).remove();
+ if ( this.nodeType === 1 || this.nodeType === 11 ) {
+ next = this.nextSibling;
+ parent = this.parentNode;
- if ( next ) {
- jQuery( next ).before( val );
- } else {
- jQuery( parent ).append( val );
+ jQuery( this ).remove();
+
+ if ( next ) {
+ next.parentNode.insertBefore( elem, next );
+ } else {
+ parent.appendChild( elem );
+ }
}
- });
- return this;
+ });
},
detach: function( selector ) {
@@ -356,7 +353,8 @@ jQuery.fn.extend({
this[i],
i === iNoClone ?
fragment :
- jQuery.clone( fragment, true, true )
+ jQuery.clone( fragment, true, true ),
+ i
);
}
}
View
@@ -1205,6 +1205,16 @@ test("replaceWith(string) for collection with disconnected element", function(){
equal(newSet.filter("span").length, 1, "ensure the new element is in the new set");
});
+// #12449
+test("replaceWith([]) where replacing element requires cloning", function () {
+ expect(2);
+ jQuery("#qunit-fixture").append("<div class='replaceable'></div><div class='replaceable'></div><div class='replaceable'></div>" );
+ // replacing set needs to be cloned so it can cover 3 replacements
+ jQuery("#qunit-fixture .replaceable").replaceWith( jQuery("<span class='replaced'></span><span class='replaced'></span>") );
+ equal( jQuery("#qunit-fixture").find(".replaceable").length, 0, "Make sure replaced elements were removed" );
+ equal( jQuery("#qunit-fixture").find(".replaced").length, 6, "Make sure replacing elements were cloned" );
+});
+
test("replaceAll(String|Element|Array<Element>|jQuery)", function() {
expect(10);
jQuery("<b id='replace'>buga</b>").replaceAll("#yahoo");