For example, say I have the following:
<span class="a b c">Has class a, b, and c</span> <span class="a">Has class a</span> <span class="b c">Has class b and c</span> <span class="a c">Has class a and c</span> <span class="a c">Has class a and c</span> <span class="a">Has class a</span>
Now, suppose I want to select all elements that have only class a.
Meaning only the second and last span
s would get selected.
Is there a simple way to do this?
$('.a').not('.b, .c')
This will select all elements with class a
that do not have b
or c
. However, they could still have class d
, e
, etc. Use Phil's answer if you really only want elements with no class other than a
.
(See below for why you might not want to do exactly what's asked in the question)
You could use the [class="a"]
"attribute equals selector", though it is brittle:
$('span[class="a"]').hide();
The problem is that if you have any whitespace in your class attribute then it will break. See this fiddle: http://jsfiddle.net/c7DP7/
You can fix this by doing a basic query on those items using a normal class selector, then further filter them while checking only a
is set (and trimming whitespace in that second filter). See this fiddle: http://jsfiddle.net/uD48E/1/
$('.a') .filter(function(index){ return $(this).attr("class").trim() == "a"; }) .hide();
The question looks like it is trying to make more "future proof" code, but that specific approach is more brittle. Rejecting all classes that aren't related to the current class you're filtering for can break things for reasons not related to class a
(like an unrelated class d
or e
that gets added later). This is important if the HTML you're applying your jQuery to might be changed in the future.
A better way to do this is to filter out only the classes that impact the meaning of class a
. Allowing for that sort of flexibility is what actually makes your code more future-proof. See maxedison's answer for the best way to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With