1

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.

Bhuwan
  • 15,392
  • 4
  • 26
  • 50
Abhi
  • 595
  • 1
  • 10
  • 17

2 Answers2

7

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>
  1. 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

  2. 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

UncaughtTypeError
  • 6,718
  • 2
  • 17
  • 35
3

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>
VXp
  • 10,307
  • 6
  • 25
  • 40
Noopur Dabhi
  • 1,687
  • 25
  • 37