Reputation: 7900
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.
Upvotes: 5
Views: 5765
Reputation: 10292
You can use jquery
.not
selector.
:updated: this will select only elements which have classes a
and 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>
Upvotes: 2
Reputation: 9662
Second edit: Using just css this selector will select both cases class 'a' in first place or in second place:
$('div[class="a b"],div[class="b a"]')
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.
Upvotes: 4