0

Im trying to apply a class to every 3 list items beginning with the 4th (3n+4). This works fine using CSS when all list items are visible.

Unfortunately, when some list items are hidden (display: none), the nth-child selector applies to those hidden list items as well.

I need the CSS to apply to only visible list items, so I did some research and tried using jQuery and the visible selector to achieve the desired result. This didn't work either.

Please see my current code below for an example.

Any help will be much appreciated. Thank you

http://codepen.io/anon/pen/xuqwf

HTML

<ul>
  <li>1</li>
  <li style="display: none;">2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li style="display: none;">6</li>
  <li>7</li>
  <li>8</li>
</ul>

CSS

ul li {
  background: yellow;
  border: 1px orange solid;
  margin: 5px;
}

ul li:nth-child(3n+4) {
  background: green;
}

.clear {
  background: red;
}

jQuery (Tried and failed)

$('ul li:visible:nth-child(3n+4)').addClass('clear');
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Oliver Evans
  • 960
  • 1
  • 20
  • 43

3 Answers3

1

Loop:

var i = 0;
$('ul li:visible').each(function(index,el) {
 if((index+1)%(3*i+4) == 0) {
   $(this).addClass('clear');
   i++;
 }
});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
1

Your JQuery is working fine. Put the hidden list items into a "sub list" within the main list container. Then apply the JQuery strictly to the "main list"

Check the fiddle http://jsfiddle.net/defmetalhead/VQ337/9/

<ul class="mainList">
  <li>1</li>
  <li>2</li>
  <li>3
    <ul>
      <li style="display: none;">3-1</li>
      <li style="display: none;">3-2</li>
      <li style="display: none;">3-3</li>
      <li style="display: none;">3-4</li>
    </ul>
  </li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

New Jquery line

$('.mainList').children('li:nth-child(3n+4)').addClass('clear');
David Aguirre
  • 1,382
  • 4
  • 15
  • 29
  • Thanks, this works as a static list but my list is created programmatically, I feel it would be a nightmare to try and achieve this. – Oliver Evans Nov 27 '13 at 17:03
0

Instead of setting every 3rd child's properties with CSS selection, add a class to them using jQuery, then replace the class when you want to change them to green. You can not override the CSS selector ul li:nth-child(3n+4).

CSS:

ul li {
background: yellow;
border: 1px orange solid;
margin: 5px;
}

.green {
 background: green;
}

.hide {
 display: none;
}

.clear {
background: red;
}

jQuery:

$('ul li:visible:nth-child(3n+4)').addClass('green');
$('ul li:visible:nth-child(3n+4)').removeClass('green').addClass('clear');
philthyfool
  • 194
  • 2
  • 5
  • 17