3
<div id="main">
 <div class="a"></div>
 <div class="b"><p>not me</p></div>
 <div class="b"></div>
 <div class="b"></div>
 <div class="c"></div>
</div> 

How we can write a selector to select all divs with class b except whose child is <p>not me</p> ?

kapa
  • 77,694
  • 21
  • 158
  • 175
King Kong
  • 2,855
  • 5
  • 28
  • 39

6 Answers6

10
$('div.b:not(:has(p))').........

Or the readable version

$('div.b').filter(function(){
    return !$(this).find('p').length;
});

If you want to match the content as well:

$('div.b').filter(function(){
    return $(this).find('p').text() !== "not me";
});

Live DEMO

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Or half-way between the two options: `$('div.b').not(':has(p)')`. Regarding the last option, I know the sample markup didn't have this problem but what if a particular div had more than one paragraph? – nnnnnn Jun 13 '12 at 10:12
3

demo http://jsfiddle.net/46nC5/1/

Since you are specifically looking for class b made a demo for you hence sharing.

In this demo you will see the not me getting fade out, rest will stay as it is.

i.e. With :not + :has it can be done

code

$('div.b:has(p)').​

or

$('div.b:not(:has(p))')
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
1
$('div.b').filter(function () {
    return $(this).find('p:contains(not me)').length == 0;
})

jsFiddle Demo

kapa
  • 77,694
  • 21
  • 158
  • 175
1

This will give you two div who have class="b" and does not have p (paragraph)

Live Demo

$('div.b:not(:has(p))')
Adil
  • 146,340
  • 25
  • 209
  • 204
1

The best way I usualy do:

$('div.b').filter(function () {
   return !$(this).hasClass('notMe');
});


<div id="main">
     <div class="a"></div>
     <div class="b notMe"><p>not me</p></div>
     <div class="b"></div>
     <div class="b"></div>
     <div class="c"></div>
</div> 
Bellash
  • 7,560
  • 6
  • 53
  • 86
0

And here's another one

$("div.b:contains('not me')")

edit: sorry, here's with not

$("div.b:not(:contains('not me'))")
Krym
  • 743
  • 6
  • 16