0

Newbie in Javascript and in English, please forgive my writing.

I've searched and came across many posts explaining how I should add a class but they are not the same as what I need to do.

I would like to add a specific class to every 4th li that is displayed (or is visible), by which I mean, I have some li that are not displayed and they should be excluded from the counter:

<section>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script language="javascript" type="text/javascript">
    <!--
      window.onload=function(){
        $('.liste li:nth-child(4)').addClass('lastli');
      };
    //-->
  </script>

  <ul class="liste">
    <li>1 Lorem</li>
    <li>2 ipsum</li>
    <li>3 dolor</li>
    <li style="display:none;">4 sin amet</li>
    <li>5 consectetur</li> <!-- add a lastli class here -->
    <li>6 aliquam</li>
    <li style="display:none;">7 lobortis</li>
    <li>8 Fusce</li>
    <li>9 fringilla</li>
    <li>10 rutrum</li> <!-- add a lastli class here -->
    <li>11 dapibus</li>
    <li style="display:none;">12 nunc</li>
    <li>13 nunc</li>
  </ul>
</section>
Harry
  • 87,580
  • 25
  • 202
  • 214

4 Answers4

4

You can do it the below way:

var lstItems = $('.liste li').filter(function () {
    return $(this).is(':visible');
});

$(lstItems).each(function (i) {
    if ((i % 4) === 3) $(this).addClass('lastli');
});
Harry
  • 87,580
  • 25
  • 202
  • 214
  • 1
    Doesn't answer the OP question of needing to select every 4th *visible* `
  • `. Some of them are not displayed and he doesn't want those included in the "every 4th item" count.
  • – Scott Sep 16 '13 at 14:43
  • No he's not. Look at the code he posted and where he's specified the class to be added. – Scott Sep 16 '13 at 14:45
  • @Scottie: I think I got what you mean now. Maybe if OP added two hidden li somewhere in between it would have been clearer. – Harry Sep 16 '13 at 14:49
  • Yeah, it's definitely open to interpretation. I'm going by his statement of `I would like to add a specific class to every 4th li displayed` to mean that he wants every 4th visible li to have the class added to it, essentially skipping over everything that's hidden. I've rescinded the downvote because hey, we're all friends here. :D //edit: drat, SO isn't letting me change my vote unless your question is edited. D: – Scott Sep 16 '13 at 14:50