Rajat Gupta
Rajat Gupta

Reputation: 26597

Select all elements except children of class

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>

Upvotes: 5

Views: 4995

Answers (1)

Jakub Kotrs
Jakub Kotrs

Reputation: 6229

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.

Upvotes: 8

Related Questions