jQuery: dealing with a space in the id attribute

前端 未结 5 2060
失恋的感觉
失恋的感觉 2020-12-01 16:29

I have an element with id=\"A B\". The following code fails:




        
相关标签:
5条回答
  • 2020-12-01 16:49

    There should not be space in an id, but this seems to works :

    $("[id=A B]")
    
    0 讨论(0)
  • 2020-12-01 16:50

    While it’s technically invalid to have a space in an ID attribute value in HTML (see @karim79’s answer), you can actually select it using jQuery.

    See http://mothereffingcssescapes.com/#A%20B:

    <script>
      // document.getElementById or similar
      document.getElementById('A B');
      // document.querySelector or similar
      $('#A\\ B');
    </script>
    

    jQuery uses a Selectors API-like syntax, so you could use $('#A\\ B'); to select the element with id="A B".

    To target the element in CSS, you could escape it like this:

    <style>
      #A\ B {
        background: hotpink;
      }
    </style>
    
    0 讨论(0)
  • 2020-12-01 16:51

    As they mentioned you shouldn't use spaces in id. But anyway, wouldn't this be working for you?

    $("[id='A B']").click(...)
    

    EDIT: yes it works, tested it!!! Don't kill me, standard-lovers!! ;-P

    0 讨论(0)
  • 2020-12-01 16:59

    Neither HTML4 nor HTML5 allows space characters in ID attribute values.

    The HTML 4.01 spec states that ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.). For the class attribute, there is no such limitation. Classnames can contain any character, and they don’t have to start with a letter to be valid.

    HTML5 gets rid of the additional restrictions on the id attribute. The only requirements left — apart from being unique in the document — are that the value must contain at least one character (can’t be empty), and that it can’t contain any space characters.

    Source:

    http://mathiasbynens.be/notes/html5-id-class

    0 讨论(0)
  • 2020-12-01 17:06
    ID tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
    

    That quote is pulled from another stackoverflow answer: jquery IDs with spaces

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