Jquery selecting an ID with a colon in it

2019-01-06 20:54发布

问题:

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 here: http://jsfiddle.net/zbX8K/1/

回答1:

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



回答2:

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


回答3:

Use the attribute equals selector.

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


回答4:

Try using an attribute selector

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

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