4

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??

3
  • 1
    your id is invalid, but if you cannot change the markup you have to find that div in some other way... you may need to post the whole html code Commented Jun 14, 2012 at 7:44
  • Weird name, I'm not sure the name is even valid. Try to name it control0 may be Commented Jun 14, 2012 at 7:45
  • I am adding an external google widget (an external .js). This id is in the code. I want to hook the div to perform my own task. Commented Jun 14, 2012 at 7:47

3 Answers 3

3

Instead of

$("#:0.control")

try

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

DEMO

or

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

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Talk about code maintenance! Good answer but I feel sorry for those who'll stumble upon this when reading his code.
3

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.

Comments

1

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 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.