Combining a class selector and an attribute selector with jQuery

后端 未结 4 953
轻奢々
轻奢々 2020-12-12 14:56

Is it possible to combine both a class selector and an attribute selector with jQuery?

For example, given the following HTML:



        
相关标签:
4条回答
  • 2020-12-12 15:09

    Combine them. Literally combine them; attach them together without any punctuation.

    $('.myclass[reference="12345"]')
    

    Your first selector looks for elements with the attribute value, contained in elements with the class.
    The space is being interpreted as the descendant selector.

    Your second selector, like you said, looks for elements with either the attribute value, or the class, or both.
    The comma is being interpreted as the multiple selector operator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).

    0 讨论(0)
  • 2020-12-12 15:13

    I think you just need to remove the space. i.e.

    $(".myclass[reference=12345]").css('border', '#000 solid 1px');
    

    There is a fiddle here http://jsfiddle.net/xXEHY/

    0 讨论(0)
  • 2020-12-12 15:18

    This code works too:

    $("input[reference=12345].myclass").css('border', '#000 solid 1px');
    
    0 讨论(0)
  • 2020-12-12 15:25

    This will also work:

    $(".myclass[reference='12345']").css('border', '#000 solid 1px');
    
    0 讨论(0)
提交回复
热议问题