How can I select an element with multiple classes in jQuery?

前端 未结 13 2404
一向
一向 2020-11-22 00:51

I want to select all the elements that have the two classes a and b.


So, only the e

相关标签:
13条回答
  • 2020-11-22 00:52

    $('.a .b , .a .c').css('border', '2px solid yellow');
    //selects b and c
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="a">a
      <div class="b">b</div>
      <div class="c">c</div>
      <div class="d">d</div>
    </div>

    0 讨论(0)
  • 2020-11-22 00:53

    You can do this using the filter() function:

    $(".a").filter(".b")
    
    0 讨论(0)
  • 2020-11-22 00:58

    var elem = document.querySelector(".a.b");

    0 讨论(0)
  • 2020-11-22 00:59

    If you want to match only elements with both classes (an intersection, like a logical AND), just write the selectors together without spaces in between:

    $('.a.b')
    

    The order is not relevant, so you can also swap the classes:

    $('.b.a')
    

    So to match a div element that has an ID of a with classes b and c, you would write:

    $('div#a.b.c')
    

    (In practice, you most likely don't need to get that specific, and an ID or class selector by itself is usually enough: $('#a').)

    0 讨论(0)
  • 2020-11-22 01:04

    For better performance you can use

    $('div.a.b')
    

    This will look only through the div elements instead of stepping through all the html elements that you have on your page.

    0 讨论(0)
  • 2020-11-22 01:06

    Vanilla JavaScript solution:-

    document.querySelectorAll('.a.b')

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