Selecting element with id having colon in Sizzle / jQuery
I have HTML that has some elements with colons IDs. For example,
<div id="i:have:colons">Get my selector!!</div>
<my:another:test> This time with tag names </my:another:test>
I want to highlight these elements using jQuery. Here are my little tries and Jsbin Demo
function escape(id) {
return id.replace( /(:|\.|\[|\])/g, '\\$1');
}
var id = "i:have:colons";
// Does not work
console.log($('#' + id).length);
// Works
console.log($("#i\\:have\\:colons").length);
var escapedId = escape(id);
// Q1. Why answer shows only 1 backslash while I used 2 in regex
console.log(escapedId); //'i\:have\:colons'
// Works
console.log($('#' + escapedId).length);
// Q2. Does not work while escapedId === 'i\:have\:colons'. How and why ?
console.log($('#' + 'i\:have\:colons').length);
Edit after TJ's answer
var tag = 'my:another:test';
console.log('Testing tag name now----');
console.log($(tag).length);
var tag2 = tag.replace(/[:]/g, '\\\\:');
// Does not work with tagnames but this works with Id
console.log($(tag2).length);
var tag3 = tag.replace(/[:]/g, '\\:');
// Q3. Why does this work with tagnames but not with ids ?
console.log($(tag3).length);
My question is in the comments in the JS code.
source to share
// Q1. Why does answer only show 1 backslash when I used 2 in regex
Because the string you used as a replacement only had one backslash, because backslashes are special in string literals. To get the actual backslash in the selector you need \\
in a string literal. But your function is escape
correct because you only need one in the current regex.
// Q2. Doesn't work yet
escapedId === 'i\:have\:colons'
. How and why?
console.log($('#' + 'i\:have\:colons').length);
For the same reason, there are no backslashes in the switch. \:
in a string literal is simple :
. You need to escape backslashes:
console.log($('#' + 'i\\:have\\:colons').length);
Options for selecting these items:
-
Use the value incorrectly
id
using a functionescape
. -
Use
getElementById
:$(document.getElementById("i:have:colons"))
-
Use an attribute selector:
$('[id="i:have:colons"]')
But it will be slower (although chances are low that it matters) since jQuery will not optimize it in the call
getElementById
.
source to share