Handling colon in element ID with jQuery

Solution 1:

You need to escape the colon using two back-slashes:

$('#test\\:abc')

Solution 2:

In short

$(document.getElementById("test:abc")) is what you should use.

Explanation: Apart from the speed gain (see further down), it is easier to handle.

Example: Say you have a function

   function doStuff(id){

       var jEle = $("#" + id); //is not safe, since id might be "foo:bar:baz" and thus fail. 
       //You would first have to look for ":" in the id string, then replace it

       var jEle = $(document.getElementById(id)); //forget about the fact 
      //that the id string might contain ':', this always works
    }

    //just to give an idea that the ID might be coming from somewhere unkown
    var retrievedId = $("foo").attr("data-target-id");
    doStuff(retrievedId); 

Speed / Timing

have a look at this jsbin which tests and compares the speed of selection methods of IDs with colons

you need to open your firebug console to get the results.

I tested it with firefox 10 and jquery 1.7.2

basically I did a select 10'000 times of a div with a colon in the id - with the different methods to achieve it. Then I compared results to a ID selection with no colon in it, the results are quite surprising.

left time in ms right selector method

299 $("#annoying\\:colon")

302 $("[id='annoying:colon']"

20 $(document.getElementById("annoying:colon"))


71 $("#nocolon")

294 $("[id='nocolon']")

especially

  71 $("#nocolon") and
299 $("#annoying\\:colon")

comes a bit as a surprise

Solution 3:

It's tripping up on the colon, obviously, because jQuery is trying to interpret it as a selector. Try using the id attribute selector.

 $('[id="test:abc"]')

Solution 4:

I would just use document.getElementById, and pass the result to the jQuery() function.

var e = document.getElementById('test:abc');
$(e) // use $(e) just like $('#test:abc')