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/
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:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With