Skip to content

Commit 25068bf

Browse files
committed
Selector: add jQuery.escapeSelector
Fixes gh-1761 Close gh-2878
1 parent a8c0194 commit 25068bf

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

src/selector-native.js

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,26 @@ var hasDuplicate, sortInput,
3737
documentElement.webkitMatchesSelector ||
3838
documentElement.mozMatchesSelector ||
3939
documentElement.oMatchesSelector ||
40-
documentElement.msMatchesSelector;
40+
documentElement.msMatchesSelector,
41+
42+
// CSS string/identifier serialization
43+
// https://drafts.csswg.org/cssom/#common-serializing-idioms
44+
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,
45+
fcssescape = function( ch, asCodePoint ) {
46+
if ( asCodePoint ) {
47+
48+
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
49+
if ( ch === "\0" ) {
50+
return "\uFFFD";
51+
}
52+
53+
// Control characters and (dependent upon position) numbers get escaped as code points
54+
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
55+
}
56+
57+
// Other potentially-special ASCII characters get backslash-escaped
58+
return "\\" + ch;
59+
};
4160

4261
function sortOrder( a, b ) {
4362

@@ -110,7 +129,14 @@ function uniqueSort( results ) {
110129
return results;
111130
}
112131

132+
function escape( sel ) {
133+
return ( sel + "" ).replace( rcssescape, fcssescape );
134+
}
135+
113136
jQuery.extend( {
137+
uniqueSort: uniqueSort,
138+
unique: uniqueSort,
139+
escapeSelector: escape,
114140
find: function( selector, context, results, seed ) {
115141
var elem, nodeType,
116142
i = 0;
@@ -140,8 +166,6 @@ jQuery.extend( {
140166

141167
return results;
142168
},
143-
uniqueSort: uniqueSort,
144-
unique: uniqueSort,
145169
text: function( elem ) {
146170
var node,
147171
ret = "",

src/selector-sizzle.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@ jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
1010
jQuery.text = Sizzle.getText;
1111
jQuery.isXMLDoc = Sizzle.isXML;
1212
jQuery.contains = Sizzle.contains;
13+
jQuery.escapeSelector = Sizzle.escape;
1314

1415
} );

test/unit/selector.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,3 +536,9 @@ QUnit.asyncTest( "Iframe dispatch should not affect jQuery (#13936)", 1, functio
536536
iframeDoc.write( "<body><form id='navigate' action='?'></form></body>" );
537537
iframeDoc.close();
538538
} );
539+
540+
QUnit.test( "Ensure escapeSelector exists (escape tests in Sizzle)", function( assert ) {
541+
assert.expect( 1 );
542+
543+
assert.equal( jQuery.escapeSelector( "#foo.bar" ), "\\#foo\\.bar", "escapeSelector present" );
544+
} );

0 commit comments

Comments
 (0)