gdoron
gdoron

Reputation: 150253

jQuery combination of :not + :contains, does it work?

(continue from other question)

<div id="main">
    <div class="a">aaaa</div>
     <div class="b"><p>not me</p></div>
     <div class="b">bbbb</div> <!-- select this-->
     <div class="b">bbbb</div> <!-- select this-->
     <div class="c">cccc</div>
</div> ​

I'm trying to select all divs with class b that doesn't have <p>not me</p> inside of them.

I tried this:

$('div.b:not(:has(p:contains(not me)))').css('color', 'red'); 

But from some unknown reason it doesn't work, funny thing is, that if I remove the :not() part:

$('div.b:has(p:contains(not me))').css('color', 'blue');

It does select the unwanted div, so the problem must be with :not

Live DEMO

I know there are other and even better ways,(I even gave some in that question) but I'm interested to know why :not + :contains doesn't seem together.

Upvotes: 0

Views: 289

Answers (4)

user19450989
user19450989

Reputation: 1

<div id="main">
    <div class="a">aaaa</div>
     <div class="b"><p>not me</p></div>
     <div class="b">bbbb</div> <!-- select this-->
     <div class="b">bbbb</div> <!-- select this-->
     <div class="b"><p>no1t me</p></div>
     <div class="c">cccc</div>
</div>
    

Try this...

$('div.b:has(p:contains(not me))').css('color', 'green');
    
$('div.b:not(:has(p))').css('color', 'red');
    
$('div.b:has(p):not(:contains(not me))').css('color', 'blue');

See the output here

Upvotes: 0

labtoy
labtoy

Reputation: 198

example of working :not + :contains

$('div.b:not(:contains("not me"))').css('color', 'cyan');

will change the color of all the div.b's that does NOT contain "not me".

Upvotes: 1

U.P
U.P

Reputation: 7442

I think it has something to do with :has

Try this:

$('div.b:not(:contains(not me))').css('color', 'red');

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074276

You could use .not rather than :not:

$('div.b').not(':has(p:contains("not me"))').css('color', 'red');

Updated fiddle

Upvotes: 3

Related Questions