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 selector to target all `<li>` elements that are not descendants of `<li>`

For example, given the following HTML

<body>
  <ul>
    <li>First</li>
    <li>
      <ul>
        <li>A</li>
        <li>B</li>
      </ul>
    </li>
    <li>Second</li>
  </ul>
</body>

I need a CSS selector that targets <li>First</li> and <li>Second</li>.

I tried

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

:not(li) li {
  declarations
}

but that matches <li>A</li> and <li>B</li> as well because while each does have an <li> as a descendant, each also has a non-<li> in their descendant list: [<body>, <ul>, <li>, <ul>].

>Solution :

You can try li:not(li li)

li:not(li li) {
  border: 1px solid red;
}
<body>
  <ul>
    <li>First</li>
    <li> <!-- this will get selected -->
      <ul>
        <li>A</li> <!-- but not this -->
        <li>B</li>
      </ul>
    </li>
    <li>Second</li>
  </ul>
</body>
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