JQuery selector to select ONLY specific 2 classes except any other?

There are many questions that require choosing items with 2 classes. But I want to ask, what if I want get elements to have only 2 classes provided and excluding any other elements that have any other additional classes ? In other words, elements with additional classes are not needed.

<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, and not the one who has classes a b c.

+4
source share
2 answers

. css, 'a' :

$('div[class="a b"],div[class="b a"]')

: :

$('.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>

:

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

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

.

+2

jquery .not.

: :, , a b.

$("[class='a b'], [class='b a']").css("background", "blue");
.a.b{
  width: 100%;
  height: 100px;
}
.c{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="a">
  <div class="a b">
    ...
  </div>
  <div class="a b c">
    ...
  </div>
</div>
+1

Source: https://habr.com/ru/post/1660621/


All Articles