Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS Select all descendants but not children

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading