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?
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.
popupbutton is the fastest.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With