4

How do I select all <div> elements except the divs that are within elements with certain classes?

Tried:

 div :not(.test div)
 div:not(.test div) 

but doesn't work!


Edit:

Here is the HTML as requested.

<div>
</div>

<span class="test">
 <div/>
</span>
LondonRob
  • 73,083
  • 37
  • 144
  • 201
Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294

1 Answers1

8

There is no space after div, so that the :not is related to it, then the second div is a child, so not a part of the :not

div:not(.test) div {
    /* style */
}

for

<div class="test">
    <div></div>
</div>
<div>
    <div></div> <!-- gets selected -->
</div>

Edit: when you added markup, the correct version would be

div :not(.test) div {
    /* style */
}

for

<div>
    <span class="test">
        <div></div>
    </span>
    <span>
        <div></div> <!-- gets selected -->
    </span>
</div>

or

span:not(.test) div {
    /* style */
}

for

<span class="test">
    <div></div>
</span>
<span>
    <div></div> <!-- gets selected -->
</span>

Because you haven't mention the span in the original question nor have you specified if the span itself was inside a div.


You should also consider using > in your selector in this case to narrow it down.

Jakub Kotrs
  • 5,823
  • 1
  • 14
  • 30
  • `:not(.test) div` is effectively the same as `div` in most cases because `:not(.test)` would still match `html`, `body` and any other higher ancestors unless all of them contained the same class. See http://stackoverflow.com/questions/7084112/css-negation-pseudo-class-not-for-parent-ancestor-elements – BoltClock Oct 03 '13 at 15:35
  • @BoltClock yes, I realise that, added a footnote and will change the selector too – Jakub Kotrs Oct 03 '13 at 15:36
  • you listed two options one for div another for span, but what if I dont know which is there, how to generalise this ? – Rajat Gupta Oct 03 '13 at 15:38
  • To generalise: `:not` should have space in front only if it is not linked to the element before it: `div :not(.test)` checks for a child without class `.test`. The brackets are whats tested, do `:not(.test) div` is for a div-child of an element without `.test`. – Jakub Kotrs Oct 03 '13 at 15:41
  • if you could, please edit the css section in this fiddle [http://jsfiddle.net/pMrkW/] to end all the doubts. – Rajat Gupta Oct 03 '13 at 15:45
  • ohk.. but this works only when `div` is enclosed within `span`. See here .. http://jsfiddle.net/pMrkW/3/ Couldn't get a generalized solution. – Rajat Gupta Oct 03 '13 at 15:54