I have two cases in my rendered HTML page.
Case 1:
<ul>
<li>A</li>
<li>B</li>
</ul>
<div class="test">Testing here</div>
Case 2:
<ul></ul>
<div class="test"></div>
In case 1, I want to apply CSS to the div if ul element contains li elements). I don't want anything for case 2. I want a pure CSS approach without any jQuery/JavaScript.
The intended behaviour can be achieved with the use of the Adjacent sibling combinator (+) and the :emptyref pseudo-class, e.g:
ul:empty + .test
Code Snippet Demonstration:
* {
box-sizing: border-box;
}
ul:empty + .test {
background: black;
color: white;
padding: 5px;
}
<ul>
<li>A</li>
<li>B</li>
</ul>
<div class="test">Testing here</div>
<ul></ul>
<div class="test">Testing here</div>
The adjacent sibling combinator (
+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element. ref
The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments or processing instructions do not affect whether an element is considered empty or not. ref
In addition to UncaughtTypeError's answer.
There is a selector :not(:empty) for applying css to element if it has a child.
Check the :not(:empty) for more details about the selector.
* {
box-sizing: border-box;
}
ul:not(:empty) + .test {
background: black;
color: white;
padding: 5px;
}
<ul>
<li>A</li>
<li>B</li>
</ul>
<div class="test">Testing here</div>
<ul></ul>
<div class="test">Testing here</div>
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