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

前端 未结 13 2405
一向
一向 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 01:06

    Group Selector

    body {font-size: 12px; }
    body {font-family: arial, helvetica, sans-serif;}
    th {font-size: 12px; font-family: arial, helvetica, sans-serif;}
    td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
    

    Becomes this:

    body, th, td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
    

    So in your case you have tried the group selector whereas its an intersection

    $(".a, .b") 
    

    instead use this

    $(".a.b") 
    
    0 讨论(0)
  • 2020-11-22 01:07

    your code $(".a, .b") will work for below multiple elements (at a same time)

    <element class="a">
    <element class="b">
    

    if you want to select element having a and b both class like <element class="a b"> than use js without coma

    $('.a.b')
    
    0 讨论(0)
  • 2020-11-22 01:10

    You can use getElementsByClassName() method for what you want.

    var elems = document.getElementsByClassName("a b c");
    elems[0].style.color = "green";
    console.log(elems[0]);
    <ul>
      <li class="a">a</li>
      <li class="a b">a, b</li>
      <li class="a b c">a, b, c</li>
    </ul>

    This is the fastest solution also. you can see a benchmark about that here.

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

    For the case

    <element class="a">
      <element class="b c">
      </element>
    </element>
    

    You would need to put a space in between .a and .b.c

    $('.a .b.c')
    
    0 讨论(0)
  • 2020-11-22 01:11

    The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

    For more information, see the overview of the different ways to combine selectors herebelow!


    Group Selector : ","

    Select all <h1> elements AND all <p> elements AND all <a> elements :

    $('h1, p, a')
    

    Multiples selector : "" (no character)

    Select all <input> elements of type text, with classes code and red :

    $('input[type="text"].code.red')
    

    Descendant Selector : " " (space)

    Select all <i> elements inside <p> elements:

    $('p i')
    

    Child Selector : ">"

    Select all <ul> elements that are immediate children of a <li> element:

    $('li > ul')
    

    Adjacent Sibling Selector : "+"

    Select all <a> elements that are placed immediately after <h2> elements:

    $('h2 + a')
    

    General Sibling Selector : "~"

    Select all <span> elements that are siblings of <div> elements:

    $('div ~ span')
    
    0 讨论(0)
  • 2020-11-22 01:17

    Just mention another case with element:

    E.g. <div id="title1" class="A B C">

    Just type: $("div#title1.A.B.C")

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