Manjoor
Manjoor

Reputation: 4199

Adding a jQuery Click handler

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

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

Instead of

$("#:0.control")

try

$('div[id="\\:0\\.control"]')

DEMO

or

$("#\\:0\\.control") // better that previous one

DEMO

Upvotes: 3

Engineer
Engineer

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

James Allardice
James Allardice

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:

enter image description here

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

Related Questions