How to select html nodes by ID with jquery when the id contains a dot?

后端 未结 8 1054
生来不讨喜
生来不讨喜 2020-11-22 08:22

If my html looked like this:


    

        
相关标签:
8条回答
  • 2020-11-22 08:31

    Guys who's looking for more generic solution, I found one solution which inserts one backward slashes before any special characters, this resolves issues related to retrieving name & ID from a div which contains special characters.

    "Str1.str2%str3".replace(/[^\w\s]/gi, '\\$&')

    returns "Str1\\.str2\\%str3"

    Hope this is useful !

    0 讨论(0)
  • 2020-11-22 08:36

    Short Answer: If you have an element with id="foo.bar", you can use the selector $("#foo\\.bar")

    Longer Answer: This is part of the jquery documentation - section selectors which you can find here: http://api.jquery.com/category/selectors/

    Your question is answered right at the beginning of the documentation:

    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 set of rules regarding valid CSS selectors. Also useful is the 
    blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
    
    0 讨论(0)
  • 2020-11-22 08:38

    You don't need to escape anything if you use document.getElementById:

    $(document.getElementById('strange.id[]'))
    

    getElementById assumes the input is just an id attribute, so the dot won't be interpreted as a class selector.

    0 讨论(0)
  • 2020-11-22 08:40

    @Tomalak in comments:

    since ID selectors must be preceded by a hash #, there should be no ambiguity here

    “#id.class” is a valid selector that requires both an id and a separate class to match; it's valid and not always totally redundant.

    The correct way to select a literal ‘.’ in CSS is to escape it: “#id\.moreid”. This used to cause trouble in some older browsers (in particular IE5.x), but all modern desktop browsers support it.

    The same method does seem to work in jQuery 1.3.2, though I haven't tested it thoroughly; quickExpr doesn't pick it up, but the more involved selector parser seems to get it right:

    $('#SearchBag\\.CompanyName');
    
    0 讨论(0)
  • 2020-11-22 08:41

    attr selection seems to be appropriate when your ID is in a variable:

    var id_you_want='foo.bar';
    $('[id="' + id_you_want + '"]');
    
    0 讨论(0)
  • 2020-11-22 08:46

    You can use an attribute selector:

    $("[id='SearchBag.CompanyName']");
    

    Or you can specify element type:

    $("input[id='SearchBag.CompanyName']");
    
    0 讨论(0)
提交回复
热议问题