From ef4e2daa48193463b36fdc297d79c6a002e4ee67 Mon Sep 17 00:00:00 2001 From: Pierre Souchay Date: Mon, 7 Nov 2022 13:43:06 +0100 Subject: Properly escape IDs in getSelector() to handle weird IDs (#35565) (#35566) --- js/src/dom/selector-engine.js | 3 ++- js/src/util/index.js | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) (limited to 'js/src') diff --git a/js/src/dom/selector-engine.js b/js/src/dom/selector-engine.js index ad10a6083..248dab494 100644 --- a/js/src/dom/selector-engine.js +++ b/js/src/dom/selector-engine.js @@ -5,7 +5,7 @@ * -------------------------------------------------------------------------- */ -import { isDisabled, isVisible } from '../util/index.js' +import { isDisabled, isVisible, parseSelector } from '../util/index.js' /** * Constants @@ -99,6 +99,7 @@ const SelectorEngine = { } selector = hrefAttribute && hrefAttribute !== '#' ? hrefAttribute.trim() : null + selector = parseSelector(selector) } return selector diff --git a/js/src/util/index.js b/js/src/util/index.js index b92eddba2..8c6922173 100644 --- a/js/src/util/index.js +++ b/js/src/util/index.js @@ -9,6 +9,20 @@ const MAX_UID = 1_000_000 const MILLISECONDS_MULTIPLIER = 1000 const TRANSITION_END = 'transitionend' +/** + * Properly escape IDs selectors to handle weird IDs + * @param {string} selector + * @returns {string} + */ +const parseSelector = selector => { + if (selector && window.CSS && window.CSS.escape) { + // document.querySelector needs escaping to handle IDs (html5+) containing for instance / + selector = selector.replaceAll(/#([^\s"#']+)/g, (match, id) => '#' + CSS.escape(id)) + } + + return selector +} + // Shout-out Angus Croll (https://goo.gl/pxwQGp) const toType = object => { if (object === null || object === undefined) { @@ -76,7 +90,7 @@ const getElement = object => { } if (typeof object === 'string' && object.length > 0) { - return document.querySelector(object) + return document.querySelector(parseSelector(object)) } return null @@ -285,6 +299,7 @@ export { isVisible, noop, onDOMContentLoaded, + parseSelector, reflow, triggerTransitionEnd, toType -- cgit v1.2.3