Selecting an ID with a colon in it with jQuery

前端 未结 4 1153
南笙
南笙 2020-11-29 09:46

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 presuma

相关标签:
4条回答
  • 2020-11-29 10:28

    Try using an attribute selector

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

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

    0 讨论(0)
  • 2020-11-29 10:30

    Use the attribute equals selector.

    $('[id="test:two"]')
    
    0 讨论(0)
  • 2020-11-29 10:31

    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>

    0 讨论(0)
  • 2020-11-29 10:45

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

    0 讨论(0)
提交回复
热议问题