Skip to content

Commit

Permalink
Escape special characters in hx-swap-oob
Browse files Browse the repository at this point in the history
  • Loading branch information
Encephala committed Nov 30, 2023
1 parent 7274454 commit 49e86e4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, "/>")) {
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions test/attributes/hx-swap-oob.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<div id='special-chars/.:,!' hx-swap-oob='true'>SwappedSpecialChars</div>");
var div = make('<div hx-get="/test">click me</div>');
make('<div id="special-chars/.:,!"></div>');
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<div id='d1' data-hx-swap-oob='true'>Swapped3</div>");
var div = make('<div data-hx-get="/test">click me</div>');
Expand Down

0 comments on commit 49e86e4

Please sign in to comment.