1

Is there an elegant way with jQuery to find elements that have class A and don't have class B, something like

$('#canvas .A !.B').each(functon() {
          do something
});

I'm pretty sure that's not going to work, but that's the idea.

I know I could do

$('#canvas .A').each(function() {
    if(!$(this).hasClass('B'){
          do something
    }
});

but that feel really clunky.

Thanks

Steve
  • 4,534
  • 9
  • 52
  • 110
  • Even if the syntax were correct, you selector isn't going to work as you've used a space, so you'd be (at best) selecting elements without class `B` that are ancestors of an element of class `A`. – user229044 Sep 25 '13 at 04:31
  • elements that have class a not b or elements that does not contain an element with class A and not B? – PSL Sep 25 '13 at 04:31

4 Answers4

6
$('#canvas .A').not(".B").each(functon() {
          do something
});

reference not

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
0

Using Jquery you can:

$(".classA").not(".classB");

Haris Krajina
  • 14,824
  • 12
  • 64
  • 81
Sean Coyne
  • 3,864
  • 21
  • 24
0

You could also do this within a single selector, such as:

$('#canvas .A:not(.B)').each(function() {
    // console.log($(this));
});
mathielo
  • 6,725
  • 7
  • 50
  • 63
0

There are two ways to do that. You can either use :not selector or .not() of jquery.

$('#canvas .A:not(.B)').each(functon() {
          do something
});

Or

$('#canvas .A').not(".B").each(functon() {
              do something
    });
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101