1

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 class="parent">

     <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.

2 Answers 2

1

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 class="parent">

  <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>

1
  • 1
    Perfect, thank you so much! Will accept as soon as I can!
    – Ood
    Commented Oct 4, 2022 at 11:04
1

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 class="parent">

  <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:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.