@@ -21,8 +21,16 @@ export default function(internals, destination, builtIn) {
2121 * @param {...(!Node|string) } nodes
2222 */
2323 destination [ 'before' ] = function ( ...nodes ) {
24+ const connectedBefore = /** @type {!Array<!Node> } */ ( nodes . filter ( node => {
25+ return node instanceof Node && Utilities . isConnected ( node ) ;
26+ } ) ) ;
27+
2428 builtIn . before . apply ( this , nodes ) ;
2529
30+ for ( const node of connectedBefore ) {
31+ internals . disconnectTree ( node ) ;
32+ }
33+
2634 if ( Utilities . isConnected ( this ) ) {
2735 for ( const node of nodes ) {
2836 if ( node instanceof Element ) {
@@ -36,8 +44,16 @@ export default function(internals, destination, builtIn) {
3644 * @param {...(!Node|string) } nodes
3745 */
3846 destination [ 'after' ] = function ( ...nodes ) {
47+ const connectedBefore = /** @type {!Array<!Node> } */ ( nodes . filter ( node => {
48+ return node instanceof Node && Utilities . isConnected ( node ) ;
49+ } ) ) ;
50+
3951 builtIn . after . apply ( this , nodes ) ;
4052
53+ for ( const node of connectedBefore ) {
54+ internals . disconnectTree ( node ) ;
55+ }
56+
4157 if ( Utilities . isConnected ( this ) ) {
4258 for ( const node of nodes ) {
4359 if ( node instanceof Element ) {
@@ -51,10 +67,18 @@ export default function(internals, destination, builtIn) {
5167 * @param {...(!Node|string) } nodes
5268 */
5369 destination [ 'replaceWith' ] = function ( ...nodes ) {
70+ const connectedBefore = /** @type {!Array<!Node> } */ ( nodes . filter ( node => {
71+ return node instanceof Node && Utilities . isConnected ( node ) ;
72+ } ) ) ;
73+
5474 const wasConnected = Utilities . isConnected ( this ) ;
5575
5676 builtIn . replaceWith . apply ( this , nodes ) ;
5777
78+ for ( const node of connectedBefore ) {
79+ internals . disconnectTree ( node ) ;
80+ }
81+
5882 if ( wasConnected ) {
5983 internals . disconnectTree ( this ) ;
6084 for ( const node of nodes ) {
0 commit comments