Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling colon in element ID with jQuery

Tags:

jquery

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

$('#test\\:abc')

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


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"]')

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') 

use two backslash \\

DEMO

as written here

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete

Reference


Referring to Toskan's answer, I updated his code to make it a bit more readable and then output to the page.

Here's the jbin link: http://jsbin.com/ujajuf/14/edit.



Also, I ran it with more iterations

Iterations:1000000

Results:    
12794   $("#annyoing\\:colon")
12954   $("[id='annyoing:colon']"
754 $(document.getElementById("annyoing:colon"))
3294    $("#nocolon")
13516   $("[id='nocolon']")

Even More:

Iterations:10000000

Results:    
137987  $("#annyoing\\:colon")
140807  $("[id='annyoing:colon']"
7760    $(document.getElementById("annyoing:colon"))
32345   $("#nocolon")
146962  $("[id='nocolon']")

try using $('#test\\:abc')