Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Is it possible to select elements with only one class from among elements with, potentially, up to 3 classes?

Tags:

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 spans would get selected.
Is there a simple way to do this?

like image 557
Josh C. Avatar asked Dec 14 '11 21:12

Josh C.


2 Answers

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

like image 151
maxedison Avatar answered Oct 20 '22 14:10

maxedison


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

like image 37
Merlyn Morgan-Graham Avatar answered Oct 20 '22 14:10

Merlyn Morgan-Graham