jQuery: select an element's class and id at the same time?

前端 未结 6 1476
难免孤独
难免孤独 2020-11-27 10:35

I\'ve got some links that I want to select class and id at the same time.

This is because I\'ve got 2 different behaviours. When a class of links got one class name

相关标签:
6条回答
  • 2020-11-27 11:02

    It will work when adding space between id and class identifier

    $("#countery .save")...

    0 讨论(0)
  • 2020-11-27 11:17

    Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

    This one didn't work for me

    $('#country.save') 
    

    But this one did:

    $('#country .save') 
    

    so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

    edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

    The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.

    0 讨论(0)
  • 2020-11-27 11:18

    In the end the same rules as for css apply.

    So I think this reference could be of some valuable use.

    0 讨论(0)
  • 2020-11-27 11:21

    You can do:

    $("#country.save")...
    

    OR

    $("a#country.save")...
    

    OR

    $("a.save#country")...
    

    as you prefer.

    So yes you can specify a selector that has to match ID and class (and potentially tag name and anything else you want to throw in).

    0 讨论(0)
  • 2020-11-27 11:21

    How about this code?

    $("a.save#country")
    
    0 讨论(0)
  • 2020-11-27 11:29
    $("a.save, #country") 
    

    will select both "a.save" class and "country" id.

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