Is there a CSS “haschildren” selector? [duplicate]

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.

Leave a Comment

techhipbettruvabetnorabahisbahis forumu