Is there a CSS "haschildren" selector?

Possible Duplicate:
Is there a CSS parent selector?

Is there a css selector I can use only if a child element exists?

Consider:

<div> <ul> <li></li> </ul> </div>

I would like to apply display:none to div only if it doesn't have at least one child <li> element.

Any selector I can use do this?


不幸的是,不幸的是,这对于CSS选择器来说是不可能的。


Sort of, with :empty but it's limited.

Example: http://jsfiddle.net/Ky4dA/3/

Even text nodes will cause the parent to not be deemed empty, so a UL inside the DIV would keep the DIV from being matched.

<h1>Original</h1>
<div><ul><li>An item</li></ul></div>

<h1>No Children - Match</h1>
<div></div>

<h1>Has a Child - No Match</h1>
<div><ul></ul></div>

<h1>Has Text - No Match</h1>
<div>text</div>

DIV {
 background-color: red;
 height: 20px;    
}

DIV:empty {
 background-color: green;
}

Reference: http://www.w3.org/TR/selectors/#empty-pseudo

If you go the script route:

// pure JS solution
​var divs = document.getElementsByTagName("div");
for( var i = 0; i < divs.length; i++ ){
    if( divs[i].childNodes.length == 0 ){ // or whatever condition makes sense
        divs[i].style.display = "none";
    }        
}​

Of course, jQuery makes a task like this easier, but this one task isn't sufficient justification to include a whole libary.


CSS does not (yet) have any parent rules unfortunately, the only way around it if you must apply it only parents that contain a specific child is with the Javascript, or more easily with a library of javascript called jQuery.

Javascript can be written in a similair way to CSS in someways, for your example we would do something like this at the bottom of our HTML page:

<script type="text/javascript">
     $('div:has(ul li)').css("color","red");
</script>

(For this you would need to include the jQuery library in your document, simply by putting the following in your <head></head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
链接地址: http://www.djcxy.com/p/22822.html

上一篇: CSS父/祖选择器

下一篇: 有没有CSS“haschildren”选择器?