Home > Blockchain >  CSS selector to target all `<li>` elements that are not descendants of `<li>`
CSS selector to target all `<li>` elements that are not descendants of `<li>`

Time:01-22

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

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

CodePudding user response:

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>

CodePudding user response:

The correct selector is:

body > ul > li {
  declarations
}
  • Related