Marc
Marc

Reputation: 6771

jQuery selector all elements not in subclass

Given this HTML (can be different) somewhere on the page:

<div id="start">
<div>
    <div class="buttons">select this</div>
    <div class="myControl">
        <div class="buttons">dont select this</div>
    </div>
    <div>
        <div class="buttons">select this</div>
    </div>
</div>
</div>​

I want to mark all elements with class buttons red:

$('#start').find('.buttons').css('color','red');​

but not if they are inside of myControl, so only the "select this" divs should be red.

In pseudocode the selector would be

Take every element with class "buttons" but ignore everything in elements with class "myControl"

I prepared a jsfiddle here.


EDIT

I wasn't aware of the fact that the start div can have the "myControl" class as well (tried to strip down the code from my project as far as possible to make it readable), so actually it looks like this (and the complete block could be nested in more divs with myControl as well).

So unfortunately the (correct for my original question) answers doesn't work in that situation, sorry for that! Any idea how to tweak one of the answers to solve this?

<div class="myControl" id="start">
<div>
    <div class="buttons">select this</div>
    <div class="myControl">
        <div class="buttons">dont select this</div>
    </div>
    <div>
        <div class="buttons">select this</div>
    </div>
</div>
</div>​

The new jsfiddle here.


SOLUTION

So the final solution was this:

$('#start').find('.buttons:not("#start div.myControl div.buttons ")')
.css('color','red');​

Upvotes: 3

Views: 3468

Answers (3)

Daniel Hallqvist
Daniel Hallqvist

Reputation: 822

$('#start').find('.buttons').filter(function(e) { return $(this).parent(".myControl").length < 1; }).css('color','red');​

Upvotes: 2

Prasad Surase
Prasad Surase

Reputation: 6574

$('#start').children('.buttons').css('color', 'red')

Upvotes: 0

YogeshWaran
YogeshWaran

Reputation: 2281

you can use .not

 $('#start').find('.buttons:not("div.myControl > div.buttons ")').css('color','red');​

jsfiddle

http://jsfiddle.net/QqRuV/3/

Upvotes: 7

Related Questions