From 49e86e4d86934c5b7c5f9ae8f00f6fe17483bbcf Mon Sep 17 00:00:00 2001 From: Encephala Date: Thu, 30 Nov 2023 23:11:08 +0100 Subject: [PATCH] Escape special characters in hx-swap-oob --- src/htmx.js | 17 ++++++++++++++++- test/attributes/hx-swap-oob.js | 10 ++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/htmx.js b/src/htmx.js index e6cd38920..ca01e12c7 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -582,6 +582,21 @@ return (function () { return str.substring(str.length - suffix.length) === suffix } + function escapeSelector(selector) { + var special_chars = /[\/\[\].,:!]/; + var result = ""; + if (selector === null) { + return null; + } + for (var i = 0; i < selector.length; i++) { + if (special_chars.test(selector[i])) { + result += "\\"; + } + result += selector[i]; + } + return result; + } + function normalizeSelector(selector) { var trimmedSelector = selector.trim(); if (startsWith(trimmedSelector, "<") && endsWith(trimmedSelector, "/>")) { @@ -777,7 +792,7 @@ return (function () { * @returns */ function oobSwap(oobValue, oobElement, settleInfo) { - var selector = "#" + getRawAttribute(oobElement, "id"); + var selector = "#" + escapeSelector(getRawAttribute(oobElement, "id")); var swapStyle = "outerHTML"; if (oobValue === "true") { // do nothing diff --git a/test/attributes/hx-swap-oob.js b/test/attributes/hx-swap-oob.js index e69c43e68..9831f1e71 100644 --- a/test/attributes/hx-swap-oob.js +++ b/test/attributes/hx-swap-oob.js @@ -38,6 +38,16 @@ describe("hx-swap-oob attribute", function () { div.innerText.should.equal("Clicked"); }) + it('handles special characters in id properly', function () { + this.server.respondWith("GET", "/test", "Clicked
SwappedSpecialChars
"); + var div = make('
click me
'); + make('
'); + div.click(); + this.server.respond(); + div.innerHTML.should.equal("Clicked"); + byId("special-chars/.:,!").innerHTML.should.equal("SwappedSpecialChars"); + }) + it('handles basic response properly w/ data-* prefix', function () { this.server.respondWith("GET", "/test", "Clicked
Swapped3
"); var div = make('
click me
');