简体   繁体   English

用于选择DIV的CSS选择器(或JavaScript,如果需要的话),其中至少包含一个UL

[英]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. 我想选择所有这些div,其中至少包含一个ul So in the above example code, that would be divs second_level_2 , fourth_level_1 and fifth_level_2 .. 因此,在上面的示例代码中,将是divs second_level_2fourth_level_1fifth_level_2

What CSS selector can I use to get this result ? 我可以使用哪个CSS选择器获得此结果?

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 .. 如果仅靠CSS无法实现,则可以使用JavaScript建议答案,尽管由于我的实际代码的性质,如果可能的话,我真的想避免这种情况。

jsfiddle 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 : 您可以使用ul将第二个类手动添加到div中:

<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. 注意:如果您在服务器上使用某些动态语言(例如PHP),则实际上可以很容易地实现它,而无需手动编码。

Or if you want to be dynamic I recommend jQuery: 或者,如果您想保持动态,我建议使用jQuery:

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

Parent selector isn't available in CSS, despite a lot of requests to add it. 父选择器在CSS中不可用,尽管有很多要求添加它。

jQuery has a nice selector, know as :has ; jQuery有一个不错的选择器,称为:has http://api.jquery.com/has-selector/ http://api.jquery.com/has-selector/

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

Would be the jQuery selector. 将是jQuery选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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