Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a CSS "haschildren" selector? [duplicate]

Tags:

css

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?

like image 962
Chaitanya Avatar asked Aug 30 '12 23:08

Chaitanya


People also ask

Is there a CSS parent selector?

The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.

Which selector is faster in CSS?

popupbutton is the fastest.

How do I apply parent child in CSS?

It's easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinators (>), which are placed between two CSS selectors. For example, div > p selects all <p> elements where the parent is a <div> element.

Can I use CSS has ()?

Presently, the CSS :has() selector is not widely supported by browsers; this selector only works in the latest version of Safari or via the experimental features flag in the latest version of Chrome. So for now, we must not use :has() in production.


1 Answers

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.

like image 87
Tim M. Avatar answered Sep 19 '22 19:09

Tim M.