48

I'm working on a pre-written module for a site, and I need to target an element with the id test:two. Now, this element has a colon in it, so jQuery is presumably and understandably seeing the 'two' as a pseudo class. Is there any way of targeting this element with jQuery?

Also, changing the ID is not possible. Believe me, if I could I would.

I've put together an example:

$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$('#test:two').css('background','green');
<script src="//code.jquery.com/jquery-1.6.3.js"></script>

<div id="test">test</div>
<div id="test:two">test two</div>
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Geoff
  • 747
  • 3
  • 11
  • 16
  • 5
    As an alternative to escaping, you can retrieve the DOM element using getElementById and then wrap it in jQuery. eg. `$(document.getElementById('test:two'))`. This technique an be useful in other cases as well. – a'r Sep 15 '11 at 16:28
  • I did some testing, see here: http://stackoverflow.com/a/11862160/533426 – Toskan Aug 08 '12 at 10:06
  • Duplicate of: [Handling colon in element id jquery](http://stackoverflow.com/questions/5552462) – hippietrail Nov 16 '12 at 13:00
  • Consider using $.escapeSelector instead of manually escaping. https://api.jquery.com/jQuery.escapeSelector/ – Matt Scilipoti Feb 20 '23 at 20:12

4 Answers4

87

Simply escape the colon with a \\:

$('#test\\:two');

http://jsfiddle.net/zbX8K/3/


See the docs: How do I select an element by an ID that has characters used in CSS notation?.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
18

From the jQuery ID Selector docs:

If the id contains characters like periods or colons you have to escape those characters with backslashes.

Because the backslash itself need to be escaped in the string, you'll need to do this:

$("#test\\:two")

$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$('#test\\:two').css('background','green');
<script src="//code.jquery.com/jquery-1.6.3.js"></script>

<div id="test">test</div>
<div id="test:two">test two</div>

You now also have the option of using the built-in CSS.escape(...) function, which takes care of any characters that could have special meaning inside of a selector expression.

$("#" + CSS.escape("test:two"))

$('#test').css('background','red');
$(document.getElementById('test:two')).css('background','blue');
$("#" + CSS.escape("test:two")).css('background','green');
<script src="//code.jquery.com/jquery-1.6.3.js"></script>

<div id="test">test</div>
<div id="test:two">test two</div>
Jeremy
  • 1
  • 85
  • 340
  • 366
13

Use the attribute equals selector.

$('[id="test:two"]')
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
7

Try using an attribute selector

$(document).ready(function() {
    $('div[id="test:two"]').each(function() {
       alert($(this).text());
    }); 
});

Fiddle: http://jsfiddle.net/zbX8K/2/

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454