Reputation: 77
I have the following 3 elements in HTML:
<span class="a b"></span>
<span class="a"></span>
<span class="a b"></span>
I want to select the element which has only class "a".
If I simply do $("span.a")
, then all three elements will be selected.
Additionally, I want to do it in a for loop because based on this I have to do some other calculation.
It looks like a simple issue but for some reason I am not able to figure it out.
Upvotes: 2
Views: 54
Reputation: 14830
A different approach than @dfsq
$('.a:not(.b)')
Select everything with class a
that does not have class b
. This also works in plain CSS selectors.
.a:not(.b) {
color: red;
}
If you want "exactly .a
and nothing else" then dfsq's solution is great. If you want more flexibility with combinations of classes then this may work better.
This snippet demonstrates it:
.a:not(.b) {
color: red;
}
<span class="a b">This span has class="a b"</span><br>
<span class="a">This one has only class="a"</span><br>
<span class="a b">This also has class="a b"</span><br>
Upvotes: 0