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

This question already has answers here:
Closed 10 years ago.
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?

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.

Nope, unfortunately that's not possible with CSS selectors.

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>

If you use jquery, you can try out this function
jQuery.fn.not_exists = function(){
return this.length <= 0;
}
if ($("div#ID > li").not_exists()) {
// Do something
}

There is another option
$('div ul').each(function(x,r) {
if ($(r).find('li').length < 1){
$(r).css('display','block'); // set display none
}
})

Related

Hide a whole div with CSS with part of it is empty

Is there a way to hide a whole div if part of it is empty? For example if "dd" is empty as shown below can I hide the whole class "test" so the keyword Restrictions does not show either. I tried .test dd:empty { display: none; } but this does not work. thanks!
<div class="test"><dt>Restrictions:</dt>
<dd></dd></div>
I don't think there's any easy way to do what you're talking about with just CSS. Better to test it server-side if you can. But if you can't here's some JS that will do the job.
<script type="text/javascript">
// handles multiple dt/dd pairs per div and hides them each conditionally
function hideIfEmpty() {
// get all the elements with class test
var els = document.getElementsByTagName('dl');
// for every 'test' div we find, go through and hide the appropriate elements
Array.prototype.map.call(els, function(el) {
var children = el.childNodes;
var ddEmpty = false;
for(var i = children.length - 1; i >= 0; i--) {
if(children[i].tagName === 'DD' && !children[i].innerHTML.trim()) {
ddEmpty = true;
} else if(children[i].tagName === 'DT') {
if(ddEmpty) {
children[i].style.display = 'none';
}
// reset the flag
ddEmpty = false;
}
}
});
}
window.addEventListener('load', hideIfEmpty);
</script>
<div class="test">
<div style="clear: both;"></div>
<dl>
<dt>Restrictions:</dt>
<dd></dd>
<dt>Other Restrictions:</dt>
<dd>Since I have content, I won't be hidden.</dd>
</dl>
</div>
Just a fair warning: the code uses some functions that may not exist in older IE, such as Array.prototype.map, String.prototype.trim, and addEventListener. There are polyfills available for these and you could also write your own pretty easily (or just do it with a for loop instead).
CSS alone can't do that. Either, you need a javascript to retrieve empty elements and hide their parents, or your CMS applies special CSS classes if there's no content.
Put as an answer as requested by #Barett.
You could update your CSS to be
.test{
display: none;
color: transparent;
}
This would make the text transparent too, but display:none should hide it anyway.
To make the div with the id test ONLY show when the dd tag is EMPTY, and you can use jQuery, try the following JavaScript along with the CSS:
if($("dd").html().length ==0)
{show();
}
Note: this solution requires jQuery, which is a JavaScript library.

dynamic stylesheet with angularjs

I have and angularjs application that fetches data via api, and builds a webpage with it.
Usually I use ng-style to create dynamic styling, but now I have to use the nth-of-type attribute that can only be used in a css stylesheet (I cannot use individual styling since the number and order of elements always change).
I have tried this naive code (in the html page):
<style ng-if="styles.sc && styles.sc.length==3">
a.mosection:nth-of-type(3n) > div {
background-color: {{styles.sc[0]}} !important;
}
a.mosection:nth-of-type(3n+1) > div {
background-color: {{styles.sc[1]}} !important;
}
a.mosection:nth-of-type(3n+2) > div {
background-color: {{styles.sc[2]}} !important;
}
</style>
But it didn't work... Apparently angular doesn't bind the data inside the style tag (the ng-if attribute does get digested properly)
Does anyone have any idea how this can be done?
Thanks!
You should checkout those three ng-*
https://docs.angularjs.org/api/ng/directive/ngClass
https://docs.angularjs.org/api/ng/directive/ngClassOdd
https://docs.angularjs.org/api/ng/directive/ngClassEven
all of them can accept functions as attributes, you can also checkout
https://docs.angularjs.org/api/ng/directive/ngStyle
which might be actually the best in your case
Thanks!
I indeed solved it by using ng-style with a function
The HTML
<div class="widget widget-people" ng-style="{backgroundColor: staggerBgColors('widget', 'widget-people', '#333333')}"></div>
<div class="widget widget-property" ng-style="{backgroundColor: staggerBgColors('widget', 'widget-property', '#24d10f')}"></div>
The scope function
$scope.staggerBgColors = function(elesClass, eleClass, defaultColor){
if (!$scope.styles || !$scope.styles.sc || $scope.styles.sc.length!=3){
return defaultColor;
}else{
var listItem = $('.'+eleClass);
var n = $('.'+elesClass).index( listItem ) % 3;
return '#' + $scope.preview.moment.sc[n];
}
}
I had to implement the same functionality of the css property "nth-of-type" using jQuery, but it works prefectly!

Applying style to a parent block depending on the child's state

With the following block structure:
<div class="container">
<div class="title"></div>
<div class="subject"></div>
</div>
is it possible to hide (display:none) a .container if it's child .subject is empty?
Thanks!
well... you could try to fake it... make title position: absolute and for container set overflow: hidden; container itself will only be visible if you put something into .subject tag. Like this:
jsfiddle example
I believe you'll have to use javascript to do this. In jQuery:
$(".container").each( function() {
if ( $(this).children('.subject').html() == '' ) {
$(this).hide();
}
} );
Example at: http://jsfiddle.net/m5jjs/
Not currently possible in pure CSS in any browser I know of.
There is a jQuery plugin cssParentSelector polyfill for the upcoming parent selector in CSS Selectors Level 4 if you already have a jQuery dependency in the project.
:empty psuedo class can be used if element has no node but you have. Need JS though.
$(".container *") {
if($.trim($(this).html()).length == 0 && $.trim($(this).text()).length == 0 ) {
$(".container").css({ "display" : "none" });
}
});

Select all sibling elements, not just following ones

The intent is to target all the other elements of the same type & same level whenever one is hovered. Tried
a:hover ~ a
Only to notice that this doesn't target the elements before the hovered one... Is there a solution with css? Or should I just somehow js my way out of this
This is a variation on the parent or < selector question (of which there are many). I know it's not quite the same, but I'm sure you can imagine how a sibling selector would be derived from a parent selector.
Jonathan Snook has an excellent blog post on why this doesn't exist, and I don't think I can do any better, so I'll leave you to read that if it interests you. Basically, it's a technically difficult job because of the way elements are selected, and it would lead to a whole world of mess in terms of code structure.
So the short answer is, this doesn't exist and you'll need to resort to JS to fix it, I'm afraid.
Edit: Just a couple of examples of fixes. Using jQuery:
$(selector).siblings().css({...});
or if you want to include the element:
$(selector).parent().children().css({...});
Or in vanilla JS:
var element = document.querySelectorAll(selector); // or getElementById or whatever
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
if (siblings[i] !== element) { // optional
siblings[i].style.color = 'red';
}
}
You can do this by using jQuery to toggle the hover states instead of CSS:
HTML:
​<div>
Link 1
Link 2
Link 3
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
CSS:
div a {color: #000;}
div a.hover {color: #00f;}
​
jQuery:
$("div a").hover(
function(){
$("div a").addClass("hover");
},
function(){
$("div a").removeClass("hover");
}
);
Fiddle

CSS if/else statement for counting list items

I need an if/else statement for my CSS which can count list items. Would this be possible?
Basically I want to say, if there are less than 10 list items, the UL container should be 200px wide, and it there are more than 10 list items, it should be 400px wide. Something like that.
Can it be done?
I would appreciate a working demo on jsFiddle, both so I can see working code, and for anyone who looks here in the future so they can see a working example and how to do it :)
CSS only does styles, but not dynamically (unless with assistance of JS). you can use the following JS snippet for the task. just to make sure, load this at the very last, just before the </body>
<script type="text/javascript">
(function resize() {
//get all lists with selected name
var lists = document.getElementsByClassName('myList');
//loop through all gathered lists
for (i = 0; i < lists.length; i++) {
//shorthand elements for easy use
var list = lists[i];
var items = list.getElementsByTagName('li');
//append class names
list.className = (items.length < 10) ? 'myList less' : 'myList more';
}
}())​
</script>
.less{
width:200px;
}
.more{
width:400px;
}​
CSS has no if else statements. You can do this easily with jQuery. Another option would be to use LESS or SCSS.
Short answer: no. CSS offers no conditional support.
Long answer: you need to use javascript or a server side language to either add a class when there are more than 10 items (or elements) in the list, or in the case of javascript, directly manipulate the style after it's loaded.
That doesn't sound possible for CSS. There are no logical if/else statements in the CSS spec. Your next best bet would probably be javascript. You could achieve this with jQuery with the following code:
if($('ul#target-list li').length < 10) {
$('ul#target-list').css('width', 200);
}
else {
$('ul#target-list').css('width', 400);
}
Pure CSS3 Solution
If you only want to support CSS3, then this does what you need:
li {
width: 200px;
}
li:nth-last-child(n+11),
li:nth-last-child(n+11) ~ li {
width: 400px;
}
But you will need to make the ul either display: inline-block or float it so that the width is controlled by the li elements themselves. This may require you to wrap the ul (display: inline-block) in a div so that it still is a block element in the flow of the page if you need it so.

Resources