Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector: element without any its children

I have a nested unordered list with one "li" element defined with identifier: [data-main]

  • 1 (must be selected)
    • 1.1
    • 1.2
  • 2

using the following html:

<ul>
  <li data-main>1 (must be selected)
    <ul>
      <li>1.1</li>
      <li>1.2</li>
    </ul>
  </li>
  <li>2</li>
</ul>

I'm trying to find the right CSS selector for selecting only element 1 without its children: 1.1 and 1.2. Selectors, I tried:

li:not([data-main]) - selects all li except main, but i need something opposite

[data-main]:not(:nth-child(1)) - selects nothing

https://jsfiddle.net/DaViking/dtqhag2t/

like image 905
Panda Avatar asked Mar 04 '16 09:03

Panda


1 Answers

What you're not realising is that the [data-main] selector in your JSFiddle demo is selecting only that top-level li element. The problem you're facing here is that this li element contains the other li elements. Those aren't selected by this selector individually, but they are contained within the element which is selected:

Example

If you want to style just the text held within the [data-main] element but not within the ul element contained within it, you'll need to override the [data-main] style declarations:

[data-main] {
  color: red;
}

[data-main] ul {
  color: initial;
}
<ul>
  <li data-main>1 (must be selected)
    <ul>
      <li>1.1</li>
      <li>1.2</li>
    </ul>
  </li>
  <li>2</li>
</ul>

If you want to place a border around the "1 (must be selected)" text and nothing else, you can wrap that text in a span element and apply styling to that instead:

[data-main] span {
  border: 1px solid red;
}
<ul>
  <li data-main>
    <span>1 (must be selected)</span>
    <ul>
      <li>1.1</li>
      <li>1.2</li>
    </ul>
  </li>
  <li>2</li>
</ul>
like image 107
James Donnelly Avatar answered Oct 22 '22 11:10

James Donnelly