views:

196

answers:

1

I want to do an addclass, but only if it doesn't have a child of a certain class.

$selector.addClass('addthisclass');

So I want:

<div class="addthisclass"><span></span></div>

And nothing on here.

<div><span class="badclass"></span></div>

Anyone know how to do this?

+9  A: 

Use the :has and :not selectors:

$("div:not(:has(span.badclass))").addClass("addthisclass");
cletus
He 'doesn't' want it to be added if it has bad class.
Chacha102
easily reversed (and done)
cletus
That's what the not is for
drs9222
Didn't know about the :has selector. Nice!
tvanfosson
oh I must of hit the page between the time you edited it and the time you posted. lol
drs9222
@drs9222, he didn't have the :not at first.
Chacha102
That is one crazy selector if you ask me. Exactly how deep does the jquery rabbit hole go?
seth
jQuery rocks! :)
SolutionYogi
@Yogi - coming around to that point of view more and more as of late.
seth
Absolutely. In fact, I just registered jqueryrocks.com and will start posting snippets like this on that site. :)
SolutionYogi