Select only elements that don't have a parent with defined class

Viewed 3155

How do I select only children that don't have a parent with a certain class in their parent tree?

This didn't work:

div:not(.dontSelect) .child

div {
  background-color: red;
  padding: 5px;
}

div:not(.dontSelect) .child {
  background-color: green;
  padding: 5px;
}
<div>
  <div class="child">
    Select this
  </div>
  <div class="dontSelect">
    <div>
      <div class="child">
        Don't select this
      </div>
    </div>
  </div>
</div>

3 Answers

I don't think you can use combinator selectors with :not as stated in the documentation:

This selector only applies to one element; you cannot use it to exclude all ancestors. For instance, body :not(table) a will still apply to links inside of a table, since <tr> will match with the :not() part of the selector.

You could try something like this:

div {
  background-color: red;
  padding: 5px;
}

.child {
  background-color: green;
  padding: 5px;
}

.dontSelect .child {
  background-color: initial;
}
<div>
  <div class="child">
    Select this
  </div>
  <div class="dontSelect">
    <div>
      <div class="child">
        Don't select this
      </div>
    </div>
  </div>
</div>

As mentioned before, you cannot use :not() to exclude ancestors in combination selectors, but can target your .child class and exclude elements with a specific parent:

.child:not(.dontSelect .child){
    background-color: green;
    padding: 5px;
}

If you can use a id for main div:

div#content {
  background-color: red;
  padding: 5px;
}

div#content > div:not(.dontSelect).child {
  background-color: green;
  padding: 5px;
}
<div id="content">
  <div class="child">
    Select this
  </div>
  <div class="dontSelect">
    <div>
      <div class="child">
        Don't select this
      </div>
    </div>
  </div>
</div>

Related