Why is “#.id” a bad selector in CSS/jQuery yet it works in an HTML anchor?

前端 未结 5 879
迷失自我
迷失自我 2021-01-07 17:16

I\'m using JSDoc. It generates ids with a period as in


If another part of the page has



        
5条回答
  •  旧时难觅i
    2021-01-07 17:58

    For HTML5 is a valid id attribute:

    There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc

    Since it isn't a valid CSS identifier, in order to use it with querySelector() or $() you should escape it like this:

    #\\.someMethodName
    

    Mozilla Developer Network:

    To match ID or selectors that do not follow the CSS syntax (by using a colon or space inappropriately for example), you must escape the character with a back slash. As the backslash is an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector):

    Be conscious that it isn't a valid HTML4 id attribute

提交回复
热议问题