1

Is there any CSS selector for selecting a parent div only if it directly contains a select inside ?

Example code:

<div class="top_level">
  <input type="radio"></input>
</div>
<div class="top_level">
  <input type="text"></input>
</div>
<div class="top_level">
  <select name="namehere">
    <option>...</option>
    <option>...</option>
    <option>...</option>
  </select>
</div>

Suppose I only want to select the third 3rd top_level class div, since it contains a select directly inside it, how would I do that ?

I did try to search around for an answer, but couldn't find any. It would have been a lot easier if parent selection was possible in CSS.

Ahmad
  • 11,274
  • 24
  • 79
  • 132
  • 1
    possible duplicate of [Is there a CSS parent selector?](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – grc Oct 06 '13 at 13:40
  • I guess the question might seem similar, but I'm not technically asking for a parent selector here. I'm asking if an element can be selected on the basis of what it contains. Technically they are different questions I would think. – Ahmad Oct 06 '13 at 13:49

2 Answers2

4

If you're using jQuery, then you can use :has :

$('div.top_level:has(select)')

If you're using only CSS, then the answer is simple : No, you don't have anything similar to select a parent.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
  • I want to avoid using JS here .. Looking for a purely CSS solution right now. If I can't find anything, then I'll move to JS. – Ahmad Oct 06 '13 at 13:40
  • @Ahmad I've edited. I'm sorry but I don't think there is a pure CSS solution. – Denys Séguret Oct 06 '13 at 13:42
  • Yeah, you're probably right. I'll see if I can get something going without CSS. If not, I'll use this and mark your answer as the chosen one. – Ahmad Oct 06 '13 at 13:43
3

You can use :empty pseudo class to check whether your container is empty (excluding line breaks).

You cannot check whether it contains a type of element. But you may be able to restructure your markup to use :empty selector

eg :

<div class="top_level">
  <input type="radio"></input>
  <div class="list"></div>
</div>
<div class="top_level">
  <input type="text"></input>
  <div class="list"></div>
</div>
<div class="top_level">
  <div class="list">
  <select name="namehere">
    <option>...</option>
    <option>...</option>
    <option>...</option>
  </select>
</div>
</div>

Now you may query like

.list:not(:emtpy) {
                // to select all lists that are non-empty
}
Arun Aravind
  • 988
  • 6
  • 8