简体   繁体   中英

CSS selector (or JavaScript if needed) for select DIV's which contain at least one UL

Suppose I have a hierarchy like this:

<div class="first_level">
  <div class="second_level_1">
    <div class="third_level_1">
      <div class="fourth_level_1">
        <ul><li></li><li></li></ul>
      </div>
      <div class="fourth_level_2">
        <div class="fifth_level_1">
        </div>
        <div class="fifth_level_2">
          <ul><li></li><li></li></ul>
        </div>
      </div>
    </div>
  </div>
  <div class="second_level_2">
    <ul><li></li><li></li></ul>
  </div>
</div>

I want to select all those divs, which contain at least one ul in them. So in the above example code, that would be divs second_level_2 , fourth_level_1 and fifth_level_2 ..

What CSS selector can I use to get this result ?

EDIT:

If it's not possible with CSS alone, you can suggest answers using JavaScript, although due to the nature of my actual code, I would really like to avoid that if possible ..

jsfiddle

Here are two options - both have downsides, but you can consider them:

You can either manually add a second class to the divs with a ul :

<div class="fourth_level_1 div_with_ul_class">

Note: If you are using some dynamic language on the server, such as PHP, this could actually be implemented fairly easily, without manual coding.

Or if you want to be dynamic I recommend jQuery:

$("div > ul").parent().addClass("div_with_ul_class");

Parent selector isn't available in CSS, despite a lot of requests to add it.

jQuery has a nice selector, know as :has ; http://api.jquery.com/has-selector/

$('div:has(ul)');

Would be the jQuery selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM