Reputation: 4199
I have following div in a page (I can not modify).
<div id=":0.control">Click me</div>
Now I want to add a jQuery Click handler
$("#:0.control").click(function () {
alert('Clicked');
}
);
Above gives error. Any solution??
Upvotes: 4
Views: 163
Reputation: 87073
Instead of
$("#:0.control")
try
$('div[id="\\:0\\.control"]')
or
$("#\\:0\\.control") // better that previous one
Upvotes: 3
Reputation: 48793
This is ugly,but it works:
$(document.getElementById(":0.control"))
In cases, when id
is stored in variable, you have to use:
var id = ":0.control";
$(document.getElementById(id))
Otherwise, when you want to use pure jQuery
, you need to add additional slashes.
More complex example:
var idArray = [":bla-bla","bla[]","commonId"];
$.each( idArray, function(i,id){
$(document.getElementById(id)) //do some stuff
//Otherwise, when using pure jQuery, we need to add slashes before ':','[',']' characters
});
Upvotes: 1
Reputation: 165971
You can escape special characters in selectors:
$("#\\:0\\.control").click(function () {
alert('Clicked');
});
Here's a working example.
Note that unless you are using the HTML5 doctype, your ID is invalid. Also note that escaping the special characters is significantly faster than using an attribute selector as in another answer:
The reason for this is that the browser can take advantage of the speed of getElementById
, rather than having to rely on querySelector
or Sizzle.
Upvotes: 3