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

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

If my html looked like this:


    

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

    One variant would be this:

    $("input[id='SearchBag.CompanyName']")
    
    0 讨论(0)
  • 2020-11-22 08:56

    This is documented in the jQuery selectors API:

    To use any of the meta-characters (such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

    In short, prefix the . with \\.

    $('#SearchBag\\.CompanyName')
    

    The problem is that . will match a class, so $('#SearchBag.CompanyName') would match <div id="SearchBag" class="CompanyName">. The escaped with \\. will be treated as a normal . with no special significance, matching the ID you desire.

    This applies to all the characters !"#$%&'()*+,./:;<=>?@[\]^`{|}~ which would otherwise have special significance as a selector in jQuery.

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