From f8b5ef2451adfacc661c26dfd77ca11e54dc6de7 Mon Sep 17 00:00:00 2001 From: Andrej Ota Date: Tue, 26 Mar 2024 15:56:49 +0000 Subject: [PATCH] Walk up the nested shadow root chain to check if the body contains element. bodyContains() currently assumes that shadow root host element is always contained in the root body. This change walks up the chain of shadow roots to find the topmost host element and verify for that one if it exists in the root body. --- src/htmx.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/htmx.js b/src/htmx.js index a24926aa9..e7b57c70e 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -764,13 +764,16 @@ var htmx = (function() { * @returns {boolean} */ function bodyContains(elt) { - // IE Fix - const rootNode = elt.getRootNode && elt.getRootNode() - if (rootNode && rootNode instanceof window.ShadowRoot) { - return getDocument().body.contains(rootNode.host) - } else { - return getDocument().body.contains(elt) + // Shortcut for older browsers missing getRootNode() to avoid checking + // the condition on every iteration. + if (!elt.getRootNode) { + return getDocument().body.contains(elt); + } + // Escape from shadow root. + while (elt.getRootNode() instanceof window.ShadowRoot) { + elt = elt.getRootNode().host; } + return getDocument().body.contains(elt); } /**