Shikhar
Shikhar

Reputation: 77

How can you select an HTML element associated only with a specific class

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

Answers (2)

Stephen P
Stephen P

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

dfsq
dfsq

Reputation: 193301

Select element by class attribute:

$("span[class='a']")

Upvotes: 5

Related Questions