jQuery selectors and backslashes

前端 未结 1 693
灰色年华
灰色年华 2021-01-18 10:15

I have a dom element that contains a fully qualified name as part of the id attribute;

My Div
相关标签:
1条回答
  • 2021-01-18 10:40

    If you can change the ID within your HTML code, find some other separator than a backslash \ for your ID so that you can make a valid ID for your selector (see here). An underscore _ would be good.

    If you can't alter the HTML, jQuery can still work with backslashes in IDs and ID selectors. Except, you'll need to use four backslashes to match each literal backslash in your ID selector:

    $('#domain\\\\element\\\\div')
    

    You achieve this by

    1. Taking the ID:

      domain\element\div
      
    2. Adding the # symbol and escaping the backslashes for the selector:

      #domain\\element\\div
      
    3. Escaping each pair of backslashes for use in JavaScript strings by doubling them (also notice the quotes):

      '#domain\\\\element\\\\div'
      
    4. Then passing the string to $() as above.

    jsFiddle

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