Skip to content
This repository was archived by the owner on Dec 7, 2022. It is now read-only.

Commit 38f7e00

Browse files
committed
fix: escape special characters to be used in a query selector string
1 parent d1c98e8 commit 38f7e00

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/js/AccessibilityUtils.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -922,6 +922,17 @@ axs.utils.namedValues = function(obj) {
922922
return values;
923923
};
924924

925+
/**
926+
* Escapes a given ID to be used in a CSS selector
927+
*
928+
* @private
929+
* @param {!String} id The ID to be escaped
930+
* @return {String} The escaped ID
931+
*/
932+
function escapeId(id) {
933+
return id.replace(/[^a-zA-Z0-9_-]/g,function(match) { return '\\' + match; });
934+
}
935+
925936
/** Gets a CSS selector text for a DOM object.
926937
* @param {Node} obj The DOM object.
927938
* @return {string} CSS selector text for the DOM object.
@@ -935,7 +946,7 @@ axs.utils.getQuerySelectorText = function(obj) {
935946

936947
if (obj.hasAttribute) {
937948
if (obj.id) {
938-
return '#' + obj.id;
949+
return '#' + escapeId(obj.id);
939950
}
940951

941952
if (obj.className) {

test/js/utils-test.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,15 @@ test("nth-of-type does not refer to a selector but a tagName", function() {
121121
equal(lastLi, document.querySelector(selector),
122122
'selector "' + selector + '" does not match element');
123123
});
124+
test('special characters in IDs are properly escaped', function() {
125+
var div = document.createElement('div');
126+
div.id = 'some.id.with.special.chars';
127+
this.fixture_.appendChild(div);
128+
var selector = axs.utils.getQuerySelectorText(div);
129+
equal(div, document.querySelector(selector),
130+
'selector "' + selector + '" does not match element');
131+
});
132+
124133

125134
module("getIdReferrers", {
126135
setup: function () {

0 commit comments

Comments
 (0)