Home > Mobile >  CSS Select all descendants but not children
CSS Select all descendants but not children

Time:10-05

I am looking for a CSS selector that selects all elements of a certain type (for example all DIV tags), that are descendants of the element with the class parent, but are NOT children of that element.

For example:

<div >

     <div>NOT THIS
          <div>THIS</div>
     </div>

     <div>NOT THIS</div>
     <div>NOT THIS</div>

     <div>NOT THIS
          <div>THIS</div>
          <div>THIS<div>THIS</div></div>
     </div>

</div>

I found the following, which doesn't work in my case, since all elements are descendants of the class parent, so this code does not work:

 .parent:not(.parent) > div {
     background-color: red;
 }

I am wondering if this is possible with the CSS selectors available. If anyone could point me in the right direction it would be very much appreciated.

CodePudding user response:

You can combine the child selector with the descendant selector for that.

First of you want to select any element that is a child of parent by using .parent > *. Then you want to add the descendant selector to select the specific elementtype (div in your case).

.parent > * div {
  color: red;
}
<div >

  <div>NOT THIS
    <div>THIS</div>
  </div>

  <div>NOT THIS</div>
  <div>NOT THIS</div>

  <div>NOT THIS
    <div>THIS</div>
    <div>THIS
      <div>THIS</div>
    </div>
  </div>

</div>

CodePudding user response:

While you've already accepted an answer, there is an alternative approach which I believe is what you intended with your non-working selector:

div {
  color: hsl(0deg 90% 60% / 0.5);
}

/* selects all <div> elements which are not the children of the
   .parent: */
.parent div:not(.parent>*) {
  color: hsl(120deg 90% 40% / 1);
}
<div >

  <div>NOT THIS
    <div>THIS</div>
  </div>

  <div>NOT THIS</div>
  <div>NOT THIS</div>

  <div>NOT THIS
    <div>THIS</div>
    <div>THIS
      <div>THIS</div>
    </div>
  </div>

</div>

References:

  • Related