Search code examples
jquerydaterangepicker

In jQuery Select element that has redundant or has two of same class


Say in this example:

<div class='a a'></div>
<div class='a a'></div>
<div class='a'></div>
<div class='a a'></div>
<div class='a a'></div>
<div class='a'></div>
<div class='a a'></div>

In jQuery, how do I select the div elements with two a classes?

I am using the daterangepicker library, just so you know I don't control the rendered tags, and there are elements in the rendered calendar that has two of a same class, I want to select those.


Solution

  • You should count the occurrences of classes to get exactly the item as you wish like below.

    $(".a").filter(function(){
      var classes = $(this).attr("class").split(/\s+/);
      var countClassA = classes.filter(c => c === "a").length;
      return countClassA > 1;
    }).addClass('selected');
    div{
       padding: 5px;
    }
    
    .selected{
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='a a'>Double AA</div>
    <div class='a a'>Double AA</div>
    <div class='a'>Single A</div>
    <div class='a a'>Double AA</div>
    <div class='a a'>Double AA</div>
    <div class='a'>Single A</div>
    <div class='a b a'>Double AA</div>