From 857f99ace07d9280bcdc64e3df05850595b5b230 Mon Sep 17 00:00:00 2001 From: Jackie Li Date: Thu, 26 Sep 2024 14:24:58 +0400 Subject: [PATCH] fix #2932: check parent is null for swap --- src/htmx.js | 13 ++++++++++--- test/core/api.js | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/htmx.js b/src/htmx.js index c21f0ec3c..7a0e1f9bb 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -1661,9 +1661,13 @@ var htmx = (function() { /** @type {Node} */ let newElt const eltBeforeNewContent = target.previousSibling - insertNodesBefore(parentElt(target), target, fragment, settleInfo) + const parentNode = parentElt(target) + if (!parentNode) { // when parent node disappears, we can't do anything + return + } + insertNodesBefore(parentNode, target, fragment, settleInfo) if (eltBeforeNewContent == null) { - newElt = parentElt(target).firstChild + newElt = parentNode.firstChild } else { newElt = eltBeforeNewContent.nextSibling } @@ -1725,7 +1729,10 @@ var htmx = (function() { */ function swapDelete(target) { cleanUpElement(target) - return parentElt(target).removeChild(target) + const parent = parentElt(target) + if (parent) { + return parent.removeChild(target) + } } /** diff --git a/test/core/api.js b/test/core/api.js index a65cbd562..f3780882a 100644 --- a/test/core/api.js +++ b/test/core/api.js @@ -403,4 +403,26 @@ describe('Core htmx API test', function() { output.innerHTML.should.be.equal('
Swapped!
') oobDiv.innerHTML.should.be.equal('OOB Swapped!') }) + + it('swap delete works when parent is removed', function() { + this.server.respondWith('DELETE', '/test', 'delete') + + var parent = make('
click me
') + var div = htmx.find(parent, '#d1') + div.click() + parent.remove() + this.server.respond() + parent.children.length.should.equal(0) + }) + + it('swap outerHTML works when parent is removed', function() { + this.server.respondWith('GET', '/test', 'delete') + + var parent = make('
click me
') + var div = htmx.find(parent, '#d1') + div.click() + parent.remove() + this.server.respond() + parent.children.length.should.equal(0) + }) })