Ramazan POLAT Ramazan POLAT - 25 days ago 14
jQuery Question

jQuery selector to select ONLY specific 2 classes, excluding any other?

There are lots of questions asking for selecting elements with 2 classes.
But I want to ask that what if I want the get elements that has only 2 provided classes and excluding any other elements that have any other additional classes? In other words, no elements with additional classes wanted.

<div class="a">
<div class="a b">
...
</div>
<div class="a b c">
...
</div>
</div>


In my case, I want to get ONLY the second div element, NOT the one with
a b c
classes.

Answer

Edit: You need to filter the selection and exclude elements with a third class:

$('.a.b')
    .filter(function() {
        return this.classList[2] == null;
    });

$('.a.b')
    .filter(function() {
    return this.classList[2] == null;
    })
    .addClass('red');
div{
  height:100px;
  width:100px;
  background:black;
  float:left;
}
.red{
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a"></div>
<div class="a b"></div>
<div class="a b c"></div>


Original:

What about:

$('.a.b:not(.c)')

which is the same as

$('.a.b').not('.c')

but simplier.