0

I have several elements that I want to use nth-child to apply a background-color to. The issue is that I need to be able to hide any of these elements on the fly using javascript. I thought I could keep the alternating colors by adding/removing an allow class, and applying nth-child to that, but to no avail. I have an example going in a jsfiddle. http://jsfiddle.net/tL40wz03/ Thanks for your help!

HTML

<div class="item allow"></div>
<div class="item allow"></div>
<div class="item allow"></div>
<div class="item allow"></div>
<div class="item allow"></div>
<div class="item allow"></div>
<div class="item allow"></div>
<div class="item"></div>
<div class="item allow"></div>
<div class="item"></div>
<div class="item allow"></div>

CSS

div {
  display: block;
  height: 100px;
  width: 100px;
}

div.allow{
    background: gray; 
}

div:nth-child(even){
  background: orange;
}
div:not(.allow){
    display:none;
}
ollien
  • 4,418
  • 9
  • 35
  • 58
  • Technically your code is working as intended. It's ignoring the two without allow and based on the number of divs at the even marks it is adding the color. Don't think your code isn't working just not selecting the right ones – Asheliahut Mar 03 '15 at 03:06
  • There are a couple of related questions here on SO. Bottom line is, `nth-child` is exactly `nth-child` and applies to even children no matter what other classes or styles they might have. –  Mar 03 '15 at 03:06
  • @torazaburo Is that to say there is no way to do what I intend to do? – ollien Mar 03 '15 at 03:08
  • @Geohut Maybe so. Bottom line is I can't figure out how to get the effect I want. Any way I could achieve this? – ollien Mar 03 '15 at 03:08
  • @torazaburo Using 'even' and 'odd' classes I assume? – ollien Mar 03 '15 at 03:09
  • possible duplicate of [css3 nth of type restricted to class](http://stackoverflow.com/questions/10921809/css3-nth-of-type-restricted-to-class) – Interrobang Mar 03 '15 at 03:22

1 Answers1

0

You'll need JS, something like

function markEven() {
    var items= document.querySelectorAll('div.item');
    var count = 0;
    for (var i = 0; i < items.length; i++) {
        var classes = items[i].classList;
        classes.toggle('even', classes.contains('allow') && ++count % 2);
    }
}

And call this every time allow is added to or removed from an element.

Then

div.item       { display: none;  background: gray;   }
div.item.allow { display: block;                     }   
div.item.even  {                 background: orange; }
  • I was hoping to avoid this, but it looks increasingly like this is the only option. Thanks. – ollien Mar 03 '15 at 03:28